Bit Fields in C
Bit fields allow you to define structures with members of specific widths in terms of bits. This is useful when you want to optimize memory usage or work with packed data structures.
#include <stdio.h>
struct Status {
unsigned int flag1 : 1; // 1-bit field
unsigned int flag2 : 2; // 2-bit field
unsigned int flag3 : 3; // 3-bit field
};
int main() {
struct Status s;
s.flag1 = 1;
s.flag2 = 2;
s.flag3 = 5;
printf("Flag 1: %u\n", s.flag1);
printf("Flag 2: %u\n", s.flag2);
printf("Flag 3: %u\n", s.flag3);
printf("Size of struct Status: %zu bytes\n", sizeof(struct Status));
return 0;
}
In this example, the struct Status contains bit fields that define the widths of individual members. This allows for efficient memory usage, as each member is allocated the specified number of bits.