c / intermediate
Snippet
Efficient Data Packing with Bit Fields
Bit fields allow defining structure members with a specific number of bits to save memory or map to hardware registers.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>struct FilePermissions {unsigned int read : 1;unsigned int write : 1;unsigned int execute : 1;unsigned int owner_id : 5;};int main() {struct FilePermissions p = {1, 0, 1, 15};printf("Size: %zu bytes\n", sizeof(p));if (p.read) printf("Read access granted.\n");return 0;}
Breakdown
1
unsigned int read : 1;
Allocates exactly 1 bit for the 'read' member.
2
unsigned int owner_id : 5;
Allocates 5 bits, allowing values from 0 to 31.