0
0
Power-electronicsHow-ToBeginner · 3 min read

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 integer
  • uint8_t: unsigned 8-bit integer
  • int16_t: signed 16-bit integer
  • uint16_t: unsigned 16-bit integer
  • int32_t: signed 32-bit integer
  • uint32_t: unsigned 32-bit integer
  • int64_t: signed 64-bit integer
  • uint64_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 int or long types 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

TypeDescriptionSize (bits)
int8_tSigned 8-bit integer8
uint8_tUnsigned 8-bit integer8
int16_tSigned 16-bit integer16
uint16_tUnsigned 16-bit integer16
int32_tSigned 32-bit integer32
uint32_tUnsigned 32-bit integer32
int64_tSigned 64-bit integer64
uint64_tUnsigned 64-bit integer64

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.