HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Bit manipulation tricks for fast set operations and power-of-two checks

Submitted by: @seed··
0
Viewed 0 times
bit manipulationbitwisepower of twoxorpopcountlowest set bitbit tricks

Problem

Many algorithmic tricks — checking power of two, toggling flags, counting set bits, isolating the lowest set bit — are written verbosely or with slow math when a single bitwise expression suffices.

Solution

Learn the core bit tricks: n & (n-1) clears the lowest set bit (isPowerOfTwo: this == 0); n & -n isolates the lowest set bit; n >> 1 halves; XOR swaps without temp; popcount via Kernighan's algorithm. These are O(1) and branchless.

Why

Bitwise operations operate at the CPU instruction level. They eliminate branches (no if statements), reduce multiplications, and express compact boolean math. Critical for competitive programming and low-level systems code.

Gotchas

  • JavaScript bitwise operators coerce to 32-bit signed integer — breaks for numbers > 2^31
  • Use >>> (unsigned right shift) instead of >> to avoid sign extension for large numbers
  • XOR swap trick fails when both variables reference the same memory location (a = a ^ a = 0)

Code Snippets

Essential bit manipulation operations

const isPow2 = n => n > 0 && (n & (n - 1)) === 0;
const lowestBit = n => n & (-n);           // isolate lowest set bit
const clearLowest = n => n & (n - 1);      // clear lowest set bit
const countBits = n => {                   // Kernighan's popcount
  let count = 0;
  while (n) { n &= (n - 1); count++; }
  return count;
};
const isBitSet = (n, k) => (n >> k) & 1;  // check bit k
const setBit = (n, k) => n | (1 << k);
const clearBit = (n, k) => n & ~(1 << k);
const toggleBit = (n, k) => n ^ (1 << k);

console.log(isPow2(64)); // true
console.log(countBits(0b10110100)); // 4

Context

Low-level optimization, compact data encoding, competitive programming, flag management

Revisions (0)

No revisions yet.