C Fixed Width Integers

C Fixed Width Integers

Fixed-width integers were introduced in C99 to ensure variables always have a predictable size (in bits), regardless of system or compiler differences.

For example, on one system an int may be 2 bytes (16-bit) while on another it may be 4 bytes (32-bit).
Fixed-width types solve this problem.

These types are defined in:

#include <stdint.h>

🔹 Exact-Width Integer Types

These guarantee that the variable is exactly the specified number of bits.

Type Signed Version Unsigned Version Size
8-bit int8_t uint8_t 1 byte
16-bit int16_t uint16_t 2 bytes
32-bit int32_t uint32_t 4 bytes
64-bit int64_t uint64_t 8 bytes

Example:

#include <stdio.h>
#include <stdint.h>
int main() {
int8_t a = -100;
uint16_t b = 65000;
int32_t c = 100000;
int64_t d = 9223372036854775807;

printf(“%d\n”, a);
printf(“%u\n”, b);
printf(“%d\n”, c);
printf(“%lld\n”, d);
}


🔹 Minimum and Fastest Integer Types

✔ Minimum-width types

Guaranteed to be at least the specified width.

Signed Unsigned
int_least8_t uint_least8_t
int_least16_t uint_least16_t
int_least32_t uint_least32_t
int_least64_t uint_least64_t

✔ Fastest integer types

Optimized for speed (may be larger than required).

Signed Unsigned
int_fast8_t uint_fast8_t
int_fast16_t uint_fast16_t
int_fast32_t uint_fast32_t
int_fast64_t uint_fast64_t

🔹 Special Type: intptr_t and uintptr_t

These are integer types that are guaranteed to hold a pointer address.

intptr_t ptrValue;
uintptr_t uptrValue;

Useful in embedded systems and low-level programming.


🔹 Format Specifiers (from inttypes.h)

For portable printing, you should include:

#include <inttypes.h>

Examples:

printf("Value: %" PRId32 "\n", (int32_t)12345);
printf("Hex: %" PRIx16 "\n", (uint16_t)255);

🔹 Example: Using All Fixed Integer Types

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main() {
uint8_t age = 25;
int16_t temp = -300;
uint32_t id = 100000;
int64_t population = 7800000000;

printf(“Age: %” PRIu8 “\n”, age);
printf(“Temperature: %” PRId16 “\n”, temp);
printf(“ID: %” PRIu32 “\n”, id);
printf(“Population: %” PRId64 “\n”, population);

return 0;
}


🧠 Why Use Fixed-Width Integers?

Benefit Reason
Portability Same size across platforms
Predictable memory usage Important in embedded systems
Binary communication Networking, file formats require exact size
Performance Optimized fixed-width data for microcontrollers

Summary

Group Example Types Purpose
Exact-width int8_t, uint32_t Same size on any system
Minimum-width int_least16_t At least specified size
Fastest-width int_fast32_t Best performance
Pointer-compatible intptr_t Store pointer as integer

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *