Bit Manipulation Patterns in C
Raw operators become engineering in patterns: set (x |= BIT), clear (x &= ~BIT), toggle (x ^= BIT), test (x & BIT) for flags; masks ((1u << n) - 1) for field extraction; alignment ((x + 7) & ~7u) for rounding up; and branchless tricks (x & (x - 1) clears the lowest set bit — the popcount loop core).
All on unsigned types, always — signed shifts and overflows are undefined or implementation-defined, and bit code is exactly where compilers exploit that. Wrap recurring patterns in static inline helpers or macros so intent (FLAG_SET vs raw &) reads at call sites.
Set, clear, toggle, test
|= sets, &= ~ clears, ^= flips, & tests — four one-liners covering nearly all flag manipulation.
Masks isolate fields
(x >> 8) & 0xFF extracts byte 1; (1u << n) - 1 builds an n-bit mask — field surgery without branches.
Align with masks
(x + 7) & ~7u rounds up to multiples of 8 — allocator alignment in one branchless expression.
Unsigned, always
Every pattern above assumes unsigned semantics — signed operands invite UB the optimizer will exploit.
#include <stdio.h> int main(void) { unsigned int perms = 0; perms |= 4u; perms |= 1u; unsigned int count = 0; unsigned int v = perms; while (v) { v &= v - 1; ++count; } printf("%u %u\n", perms, count); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.