Learn C
#include "structstypes/bitfields.h"

Bit-Fields in C

#concept

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.

#how it works
1

Widths after colons

unsigned int ready : 1; reserves exactly one bit — values beyond the width truncate silently.

2

Register modeling

Named fields over a status word read as documentation — ready instead of (reg >> 3) & 1 everywhere.

3

Layout is implementation-defined

Bit order, packing, and int signedness vary by compiler — verify against your target, never assume.

4

No addresses

&s.ready is illegal — bits aren't bytes, so bit-fields can't be pointed at or passed by reference.

#example
#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;
}
Output
1 65
1The initializer fills ready with 1 (its single bit) and code with 65 (fits in 7 bits).
2Both read back as ordinary unsigned values with %u.
3Two logical fields share minimal storage — the whole point of the feature.
#use cases
Hardware status registers with per-bit documented meanings
Protocol headers packing flags and small codes densely
Memory-tight embedded tables with sub-byte fields
Preferring shifts/masks when layout must be portable

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.