← Back to C Course | Chapter 1: Introduction & Basics | Lesson 21 of 21

C Fixed-Width Integers

The Portability Problem

Plain types like int and long don't have a guaranteed size in the C standard -- int is commonly 32 bits today but was 16 bits on older systems, so code that assumes a specific width can silently misbehave when compiled on a different platform.

Example: The Portability Problem

c
#include <stdio.h>
int main() {
	printf("int size here: %zu bytes", sizeof(int));
	return 0;
}

Signed Fixed-Width Types

<stdint.h> defines int8_t, int16_t, int32_t, and int64_t, each guaranteed to be exactly that many bits wide on every conforming platform, which is exactly what protocol formats, file formats, and hardware registers need.

Example: Signed Fixed-Width Types

c
#include <stdio.h>
#include <stdint.h>
int main() {
	int32_t id = 100000;
	printf("%d", id);
	return 0;
}

Unsigned Fixed-Width Types

The unsigned counterparts uint8_t, uint16_t, uint32_t, and uint64_t follow the same naming pattern and are the standard choice for raw byte buffers, bit flags, and anything that should never represent a negative value.

Example: Unsigned Fixed-Width Types

c
#include <stdio.h>
#include <stdint.h>
int main() {
	uint8_t flags = 255;
	printf("%u", flags);
	return 0;
}

Printing Fixed-Width Values

Because the underlying type behind int32_t can vary by platform, printf format specifiers like %d aren't strictly portable for it -- <inttypes.h> provides macros like PRId32 and PRIu64 that expand to the correct specifier for each fixed-width type.

Example: Printing Fixed-Width Values

c
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main() {
	int32_t id = 42;
	printf("%" PRId32, id);
	return 0;
}

When to Use Fixed-Width Types

Reach for fixed-width types when exact size matters -- binary file formats, network packets, embedded registers -- but for everyday counters and loop variables, plain int remains simpler and is often what the platform's CPU handles most efficiently.

Example: When to Use Fixed-Width Types

c
#include <stdio.h>
#include <stdint.h>
int main() {
	int32_t filePacketSize = 1024;
	int loopCounter = 0;
	printf("%d %d", filePacketSize, loopCounter);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.