Fixed-width integers let you store numbers using a set number of bits. This helps you control memory and avoid surprises when your program runs on different devices.
0
0
Fixed-width integers (uint8_t, uint16_t, uint32_t) in Embedded C
Introduction
When you need to save memory by using the smallest number type that fits your data.
When you want your program to behave the same on different computers or microcontrollers.
When working with hardware registers that require exact bit sizes.
When sending data over a network or storing it in files where size matters.
When you want to avoid errors caused by integer size differences.
Syntax
Embedded C
#include <stdint.h> uint8_t smallNumber; // 8-bit unsigned integer uint16_t mediumNumber; // 16-bit unsigned integer uint32_t largeNumber; // 32-bit unsigned integer
These types are defined in the stdint.h header.
They always have the same size on any platform, unlike int or long.
Examples
Here we declare three variables with different fixed sizes to store numbers of different ranges.
Embedded C
#include <stdint.h> uint8_t age = 25; // can store 0 to 255 uint16_t distance = 1000; // can store 0 to 65535 uint32_t population = 1000000; // can store 0 to 4,294,967,295
Using
uint8_t is handy when you want to work with bits directly.Embedded C
#include <stdint.h> uint8_t flags = 0b00001111; // 8 bits, useful for bit operations
Sample Program
This program shows how to declare and print fixed-width unsigned integers. It prints the values stored in each variable.
Embedded C
#include <stdio.h> #include <stdint.h> int main() { uint8_t small = 255; uint16_t medium = 50000; uint32_t large = 3000000000U; printf("small (uint8_t) = %u\n", small); printf("medium (uint16_t) = %u\n", medium); printf("large (uint32_t) = %u\n", large); return 0; }
OutputSuccess
Important Notes
Unsigned types like uint8_t can only store zero or positive numbers.
Using fixed-width integers helps avoid bugs caused by different integer sizes on different machines.
Remember to include stdint.h to use these types.
Summary
Fixed-width integers store numbers using a fixed number of bits.
They help write portable and memory-efficient code.
Use uint8_t, uint16_t, and uint32_t for 8, 16, and 32-bit unsigned numbers.