Bit Manipulation Applications (Flags, Optimization)
Bit Manipulation Applications (Flags, Optimization)
- Flags: pack booleans into bits to save space
- Masks: enable/disable features via
x & maskorx | mask - Arithmetic tricks: fast parity, power-of-two checks (
(x & (x-1))===0)
// Set, clear, toggle, test bit k
function setBit(x,k){ return x | (1<<k) }
function clearBit(x,k){ return x & ~(1<<k) }
function toggleBit(x,k){ return x ^ (1<<k) }
function testBit(x,k){ return ((x>>k) & 1)===1 }
// Iterate all submasks of a mask
for (let s=mask; s; s=(s-1)&mask) { /* ... */ }
Patterns common in competitive programming, low-level code, and bitset-heavy data processing.

