C - Bit Fields

Bit-fields pack multiple boolean or small integer values into a struct with explicit bit widths.

Example

#include <stdio.h>

struct Flags {
  unsigned int a:1;
  unsigned int b:2;
  unsigned int c:5;
};

int main(void) {
  struct Flags f = {1, 3, 17};
  printf("%u %u %u\n", f.a, f.b, f.c);
}

Common Pitfalls

  • Implementation-defined layout and endianness; avoid for portable file/network formats.
  • Bit-field types must be integer types.