CC Explainer
C · 3 · Structs, Unions & I/O14 / 35 · 40%

Bitfields & Bit Manipulation

Pack flags into single bits — and know what the standard does not guarantee.

Examples: unsigned x : 3, &, |, ^, <<

shortcuts: ← prev · → next · M mark
1

Bitwise Toolkit

Set, clear, toggle and test individual bits.

Example
example
#define BIT(n)  (1u << (n))

flags |=  BIT(3);          // set bit 3
flags &= ~BIT(3);          // clear bit 3
flags ^=  BIT(3);          // toggle bit 3
if (flags & BIT(3)) { }    // test bit 3
2

Bitfield Structs

Declare exact bit widths inside a struct.

Example
example
struct Packet {
    unsigned version : 4;
    unsigned type    : 4;
    unsigned flags   : 8;
    unsigned length  : 16;
};   // often 4 bytes total
WATCH OUT
Bit order and padding of bitfields are implementation-defined. Never use them for on-the-wire formats — shift and mask manually instead.
3

Masks & Extraction

Pull a field out of a packed word with shift + mask.

Example
example
uint32_t word = 0xDEADBEEF;
uint8_t  hi   = (word >> 24) & 0xFF;   // 0xDE
uint16_t low  =  word        & 0xFFFF; // 0xBEEF
Output
hi = 0xDE, low = 0xBEEF
4

Common Traps

Shifting is easier to get wrong than it looks.

Common pitfalls
  • ✕Shifting by >= the width of the type is undefined (1 << 32 on a 32-bit int).
  • ✕Shifting a signed negative value left is undefined.
  • ✕1 << 31 overflows int — write 1u << 31.
  • ✕Right-shifting a signed negative value is implementation-defined.