0 day streak
c / expert
Snippet

Bit-fields and Structural Memory Packing

Bit-fields allow the definition of structure members with explicit bit widths. This is essential for hardware-level programming or compacting data for network protocols. However, bit-field layout is implementation-defined, meaning the ordering and padding may vary across compilers and architectures.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdint.h>
struct NetworkFlags {
uint8_t is_active : 1;
uint8_t protocol : 3;
uint8_t priority : 4;
};
int main() {
struct NetworkFlags flags = {1, 5, 12};
printf("Size of struct: %zu byte\n", sizeof(flags));
printf("Active: %u, Proto: %u, Prio: %u\n",
flags.is_active, flags.protocol, flags.priority);
return 0;
}
Breakdown
1
uint8_t is_active : 1;
Allocates exactly 1 bit for the 'is_active' flag within a uint8_t storage unit.
2
sizeof(flags)
Even with multiple bit-fields, the compiler packs them into the smallest possible underlying integer types.