Bit Operations

Here are concise notes on using bitwise operators in JavaScript โ€” useful for interviews and coding practice:


๐Ÿ”น Basics

JavaScript stores numbers as 64-bit floating point, but bitwise operators work on 32-bit signed integers.


๐Ÿ”น Common Bitwise Operators

Operator Symbol Example Meaning
AND & 5 & 3 = 1 Bit is 1 only if both bits are 1
OR | 5 | 3 = 7 Bit is 1 if at least one bit is 1
XOR ^ 5 ^ 3 = 6 Bit is 1 if bits differ
NOT ~ ~5 = -6 Flips all bits (2โ€™s complement)
Left Shift << 5 << 1 = 10 Shift left, fill with 0
Right Shift (Sign-propagating) >> 5 >> 1 = 2 Shift right, keep sign bit
Unsigned Right Shift >>> -5 >>> 1 = 2147483645 Shift right, fill with 0

๐Ÿ”น Useful Tricks

  1. Check even/odd
let x = 7;
console.log(x & 1 ? "Odd" : "Even"); // Odd
  1. Swap two numbers without temp
let a = 5, b = 9;
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log(a, b); // 9, 5
  1. Multiply or divide by 2
console.log(5 << 1); // 10  (5 * 2)
console.log(20 >> 2); // 5  (20 / 4)
  1. Check if k-th bit is set
let n = 13; // 1101
let k = 2;  // (0-indexed from right)
console.log((n & (1 << k)) !== 0); // true (bit is set)
  1. Set a bit
n = n | (1 << k);
  1. Clear a bit
n = n & ~(1 << k);
  1. Toggle a bit
n = n ^ (1 << k);
  1. Count set bits (Brian Kernighanโ€™s Algo)
function countBits(n) {
  let count = 0;
  while (n > 0) {
    n = n & (n - 1); // clears the lowest set bit
    count++;
  }
  return count;
}
console.log(countBits(29)); // 4 (11101 has 4 set bits)

Pasted image 20250817152506.png

๐Ÿ”น Common Use Cases