Skip to content

C Bit Fields

Bit fields allow you to specify the exact number of bits for struct members.

1. Bit Field Definition

c
struct Flags {
    unsigned int flag1 : 1;
    unsigned int flag2 : 1;
    unsigned int flag3 : 2;
    unsigned int reserved : 28;
};

2. Using Bit Fields

c
struct Flags flags;
flags.flag1 = 1;
flags.flag2 = 0;
flags.flag3 = 3;

3. Memory Efficiency

c
// Without bit fields: 4 bytes per int
// With bit fields: packed into fewer bytes
printf("Size: %zu\n", sizeof(struct Flags));

4. Applications

  • Hardware register mapping
  • Protocol headers
  • Memory-critical applications

Content is for learning and research only.