Skip to main content
Intermediate ~13 min read

Bit Manipulation

Think in binary: masks, shifts, and XOR tricks that turn some O(n) or O(n²) problems into one-liners.

Prerequisites: Big O Notation & Time Complexity

Every integer is already a row of bits, and the CPU can operate on that whole row in a single instruction. Bit manipulation is the craft of using that fact: instead of an array of booleans costing 8 bits each (or more), one 32-bit integer stores 32 flags; instead of arithmetic division, a right shift; instead of a hash set for "which numbers have I seen", sometimes a single XOR accumulator.

Six operators do everything. AND (&) keeps bits where both inputs have 1s, it masks. OR (|) sets bits. XOR (^) keeps bits where exactly one input has a 1, it flips and, crucially, self-annihilates: x ^ x = 0 and x ^ 0 = x. NOT (~) inverts. Left shift (<<) multiplies by two per position; right shift (>>) divides, discarding remainder bits. Every classic trick is a composition of these six.

The everyday toolkit

bit-toolkit.js
// Test / set / clear / toggle bit i (0-indexed from the right)
const test   = (x, i) => (x & (1 << i)) !== 0;
const setBit = (x, i) => x | (1 << i);
const clear  = (x, i) => x & ~(1 << i);
const toggle = (x, i) => x ^ (1 << i);

// Parity without %:  even ⇔ last bit is 0
const isEven = (x) => (x & 1) === 0;

// Power of two: exactly one bit set ⇔ n & (n-1) clears it entirely
const isPowerOfTwo = (n) => n > 0 && (n & (n - 1)) === 0;

// Multiply / divide by 2^k
const fastDouble = (x) => x << 1;   // x * 2
const fastHalf   = (x) => x >> 1;   // ⌊x / 2⌋

// The classic: find the single number where every other appears twice
function singleNumber(nums) {
  let acc = 0;
  for (const n of nums) acc ^= n;   // pairs cancel (x^x=0), loner survives
  return acc;                       // O(n) time, O(1) space, no hash set
}

// Count set bits (Brian Kernighan: each loop removes the lowest set bit)
function popcount(n) {
  let count = 0;
  while (n !== 0) { n &= n - 1; count++; }
  return count;
}

Cost summary

Operation / caseCostNotes
Any single bitwise operationO(1)one CPU instruction on machine-width integers
XOR loner scanO(n)vs O(n) space for a hash set
Subset enumeration with masksO(2ⁿ)mask = one subset; the honest way to brute-force n ≤ ~20

JavaScript bitwise ops work on 32-bit integers, values beyond ±2³¹ need BigInt or splitting. Mentioning this boundary signals real experience.

Practice

What is 12 & 10 in decimal? (12 = 1100₂, 10 = 1010₂)

Reveal explanation

1100₂ & 1010₂ = 1000₂ = 8. Only bit 3 is set in both inputs.

Check your understanding

  1. 1.Why does n & (n − 1) === 0 detect powers of two?
  2. 2.In the single-number problem (all values appear twice, one appears once), why does XOR find it?
  3. 3.You need to track 32 on/off feature flags for a user. Most memory-frugal representation?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going