Binary System & Bit Manipulation

Easy

Computers store everything as bits. Understanding binary representation, signed numbers, and bitwise operations lets you reason about memory, speed, and many interview tricks like XOR cancellation or power-of-two checks.

Interactive Visualization

Step 1 / 3Pick a number
13
13
=
0
0
0
0
1
1
0
1
76543210
13 = 8 + 4 + 1
13 in binary sets bits 3, 2, and 0.
Why it matters

Binary numbers are just sums of powers of two. Knowing bit positions makes mask math fast.

1 / 3

Key Points

  • Binary is base-2: each bit is a power of two (1, 2, 4, 8, ...)
  • A byte is 8 bits; unsigned 8-bit range is 0-255
  • Signed integers typically use two's complement (highest bit is the sign)
  • Bitwise ops (& | ^ ~) operate per-bit, not per-number
  • Shifts (<< >> >>>) move bits; in JS, bitwise ops use 32-bit signed integers
  • Bit masks let you set, clear, toggle, or test specific bits quickly

Code Examples

Decimal to Binary (manual)

function toBinary(n) {
  let bits = ''
  let value = n

  while (value > 0) {
    bits = (value & 1) + bits
    value = value >> 1
  }

  return bits || '0'
}

const n = 13
console.log(n, '->', toBinary(n)) // 1101

Repeatedly divide by 2 and record remainders (LSB first)

Bitwise AND / OR / XOR

const a = 12 // 1100
const b = 10 // 1010

console.log(a & b) // 8  (1000)
console.log(a | b) // 14 (1110)
console.log(a ^ b) // 6  (0110)

Each operator combines bits independently

Bit Masks (set, clear, toggle, test)

const READ = 1 << 0  // 0001
const WRITE = 1 << 1 // 0010
const EXEC = 1 << 2  // 0100

let perms = 0
perms = perms | READ   // set READ
perms = perms | EXEC   // set EXEC

const canWrite = (perms & WRITE) !== 0
perms = perms ^ EXEC   // toggle EXEC

Masks make flag operations O(1) and very compact

Common Mistakes

  • Forgetting JS bitwise ops are 32-bit signed (values may overflow)
  • Confusing XOR (^) with OR (|)
  • Using >> instead of >>> when you need zero-fill right shift
  • Shifting by more than 31 bits (JS masks the shift count)

Interview Tips

  • Use n & (n - 1) to clear the lowest set bit
  • XOR cancels pairs: a ^ a = 0, a ^ 0 = a
  • Bitmask enumeration: 0..(1 << n) - 1 can represent subsets
  • Mention two's complement when negatives appear in bit problems

Practice Problems

Related Concepts