How to Declare Fixed Width Integer Types in Embedded C
In Embedded C, use the
stdint.h header to declare fixed width integer types like int8_t, uint16_t, and int32_t. These types guarantee exact bit sizes, which is essential for hardware-level programming and portability.Syntax
Include the stdint.h header and use the predefined types for fixed width integers:
int8_t: signed 8-bit integeruint8_t: unsigned 8-bit integerint16_t: signed 16-bit integeruint16_t: unsigned 16-bit integerint32_t: signed 32-bit integeruint32_t: unsigned 32-bit integerint64_t: signed 64-bit integeruint64_t: unsigned 64-bit integer
These types ensure your variables have the exact number of bits regardless of the platform.
c
#include <stdint.h> int8_t mySigned8BitInt; uint16_t myUnsigned16BitInt; int32_t mySigned32BitInt;
Example
This example shows how to declare fixed width integers and print their sizes to confirm their bit widths.
c
#include <stdio.h> #include <stdint.h> int main() { int8_t a = -10; uint16_t b = 500; int32_t c = 100000; printf("a (int8_t) = %d, size = %zu bytes\n", a, sizeof(a)); printf("b (uint16_t) = %u, size = %zu bytes\n", b, sizeof(b)); printf("c (int32_t) = %d, size = %zu bytes\n", c, sizeof(c)); return 0; }
Output
a (int8_t) = -10, size = 1 bytes
b (uint16_t) = 500, size = 2 bytes
c (int32_t) = 100000, size = 4 bytes
Common Pitfalls
Common mistakes include:
- Not including
stdint.h, which means fixed width types are undefined. - Using regular
intorlongtypes that vary in size across platforms. - Assuming sizes without checking
sizeof().
Always include stdint.h and prefer fixed width types for embedded systems to avoid portability issues.
c
#include <stdio.h> // Wrong: no fixed width types, size may vary int main() { int a = -10; // size depends on platform printf("a = %d, size = %zu bytes\n", a, sizeof(a)); return 0; } // Right: use fixed width types #include <stdint.h> int main() { int8_t a = -10; printf("a = %d, size = %zu bytes\n", a, sizeof(a)); return 0; }
Quick Reference
| Type | Description | Size (bits) |
|---|---|---|
| int8_t | Signed 8-bit integer | 8 |
| uint8_t | Unsigned 8-bit integer | 8 |
| int16_t | Signed 16-bit integer | 16 |
| uint16_t | Unsigned 16-bit integer | 16 |
| int32_t | Signed 32-bit integer | 32 |
| uint32_t | Unsigned 32-bit integer | 32 |
| int64_t | Signed 64-bit integer | 64 |
| uint64_t | Unsigned 64-bit integer | 64 |
Key Takeaways
Always include
stdint.h to use fixed width integer types in Embedded C.Use types like
int8_t and uint16_t to guarantee exact bit sizes.Avoid using plain
int or long for hardware-level programming due to size variability.Check variable sizes with
sizeof() to confirm expected widths.Fixed width types improve code portability and reliability in embedded systems.