Bit-Fields in C
Bit-fields pack tiny integers into shared storage: struct { unsigned int ready : 1; unsigned int code : 7; } fits a flag plus a 7-bit value in one byte-ish unit. They model hardware registers and protocol headers where each field owns a fixed bit range.
The price is portability: layout order, padding, and whether plain int bit-fields are signed are all implementation-defined. Bit-fields suit matching external layouts on one toolchain; manual masks and shifts suit portable bit code. Never take their address — bit-fields aren't addressable.
Widths after colons
unsigned int ready : 1; reserves exactly one bit — values beyond the width truncate silently.
Register modeling
Named fields over a status word read as documentation — ready instead of (reg >> 3) & 1 everywhere.
Layout is implementation-defined
Bit order, packing, and int signedness vary by compiler — verify against your target, never assume.
No addresses
&s.ready is illegal — bits aren't bytes, so bit-fields can't be pointed at or passed by reference.
#include <stdio.h> struct Flags { unsigned int ready : 1; unsigned int code : 7;}; int main(void) { struct Flags f = {1, 65}; printf("%u %u\n", f.ready, f.code); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.