Learn C
#include "advanced/bit_patterns.h"

Bit Manipulation Patterns in C

#concept

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.

#how it works
1

Set, clear, toggle, test

|= sets, &= ~ clears, ^= flips, & tests — four one-liners covering nearly all flag manipulation.

2

Masks isolate fields

(x >> 8) & 0xFF extracts byte 1; (1u << n) - 1 builds an n-bit mask — field surgery without branches.

3

Align with masks

(x + 7) & ~7u rounds up to multiples of 8 — allocator alignment in one branchless expression.

4

Unsigned, always

Every pattern above assumes unsigned semantics — signed operands invite UB the optimizer will exploit.

#example
#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;
}
Output
5 2
1Setting bit 2 (value 4) then bit 0 (value 1) builds binary 101 = 5.
2v &= v - 1 clears the lowest set bit per pass — two passes to reach zero, so count is 2.
35 2 prints — value plus popcount from one branchless idiom.
#use cases
Permission and feature flags with set/clear/test one-liners
Protocol field extraction with shift-and-mask
Allocator alignment rounding without division
Popcount and lowest-bit tricks in bitsets and Bloom filters

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.