Bit Manipulation

Data Structures & Algorithms · Strings, Bits & Patterns · Intermediate · 20 min

Read numbers as rows of switches and use AND, OR, XOR, NOT and shifts to test, set and clear bits, count ones with x & (x - 1), find the single number with XOR, and list subsets with bitmasks.

A number is a row of light switches. AND, OR and XOR compare two rows switch by switch; a shift slides the whole row left or right.

The idea in everyday words

Imagine a panel of 8 light switches, each labelled 128, 64, 32, 16, 8, 4, 2, 1. Whatever lights are on add up to the number: on at 8 and 4 means 12. Bit operations are just rules for combining two panels switch by switch: 'on if both are on' (AND), 'on if either is on' (OR), 'on if they differ' (XOR).

Binary: counting with only 0 and 1

Decimal uses place values 1, 10, 100... Binary uses 1, 2, 4, 8, 16..., each place worth double the one to its right. Each 0/1 digit is a bit.

place 8 4 2 1 value
5 0 1 0 1 4 + 1 = 5
12 1 1 0 0 8 + 4 = 12
15 1 1 1 1 15
print(bin(12), int("1100", 2), format(5, "08b"))
print(bin(12).count("1"))      # how many 1 bits

Bit 0 is the rightmost (the 1s place). Bit i is worth 2**i, which you can also write as 1 << i.

Always read bits from the right. 6 is 110: bit 0 (rightmost) is off, bit 1 is on, bit 2 is on. Reading from the left only seems to work for numbers like 5 = 101 that look the same both ways.

The six operators

They work on each pair of bits independently:

Operator Name Rule per bit 12 op 10 (1100, 1010)
a & b AND 1 only if both are 1 1000 = 8
a | b OR 1 if either is 1 1110 = 14
a ^ b XOR 1 if they differ 0110 = 6
~a NOT flip every bit ~12 = -13 in Python
a << k left shift slide left k places, fill with 0 12 << 1 = 24 (× 2)
a >> k right shift slide right k places, drop bits 12 >> 1 = 6 (// 2)
a, b = 12, 10
print(a & b, a | b, a ^ b, a << 1, a >> 1, ~a)

Why is ~12 equal to -13? Python ints have unlimited size and use two's complement for negatives, where ~x == -x - 1. To flip only the lowest 8 bits, use x ^ 0xFF. (JavaScript bitwise operators work on 32-bit integers, so very big numbers behave differently there.)

XOR's superpowers: x ^ x = 0, x ^ 0 = x, and order does not matter.

Masks: test, set, clear and toggle one bit

A mask is a number with 1s only where you want to act. 1 << i has a single 1 at bit i.

Goal Code Why
Is bit i on? (x >> i) & 1 slide bit i to the end, keep only it
Turn bit i on x | (1 << i) OR with 1 forces it on
Turn bit i off x & ~(1 << i) AND with 0 forces it off
Flip bit i x ^ (1 << i) XOR with 1 flips it
x = 0b1010            # 10
print((x >> 1) & 1)   # bit 1 is on -> 1
print(x | (1 << 0))   # 11
print(x & ~(1 << 3))  # 2
print(x ^ (1 << 2))   # 14
print(1 << 3 - 1)     # 4, not 7: minus runs before the shift

Precedence traps: + and - run before shifts, so 1 << 3 - 1 is 1 << 2. And in C, Java and JavaScript, == runs before &, so x & 1 == 1 means x & (1 == 1) there. Python happens to do & first, but brackets make your intent clear in every language: (x & 1) == 1, (1 << 3) - 1.

Three classic tricks

1. x & (x - 1) clears the lowest 1 bit. Subtracting 1 flips the lowest 1 to 0 and every 0 below it to 1. ANDing with x then wipes all of those.

x = 12                    # 1100
print(bin(x - 1))         # 1011
print(bin(x & (x - 1)))   # 1000

def count_ones(x):        # loop runs once per 1 bit (Kernighan's trick)
    count = 0
    while x:
        x &= x - 1
        count += 1
    return count

def is_power_of_two(x):   # exactly one 1 bit
    return x > 0 and x & (x - 1) == 0

print(count_ones(13), is_power_of_two(16), is_power_of_two(18))

2. XOR cancels pairs. XOR every number together: pairs become 0 and only the number that appears once survives. O(n) time, O(1) space, no hash map.

nums = [4, 1, 2, 1, 2]
acc = 0
for x in nums:
    acc ^= x
print(acc)

3. x & -x isolates the lowest 1 bit: 12 & -12 is 4. Used in Fenwick trees.

Bitmasks as sets: every subset

For a list of n items, a number from 0 to 2**n - 1 can describe a subset: bit i is on → item i is in the subset.

mask binary subset of [a, b, c]
0 000 []
1 001 [a]
5 101 [a, c]
6 110 [b, c] (bit 0 is off, so no a)
7 111 [a, b, c]
items = ["a", "b", "c"]
n = len(items)
for mask in range(1 << n):
    print(format(mask, "03b"), [items[i] for i in range(n) if (mask >> i) & 1])

Counting from 0 to 2**n - 1 visits every combination of on/off switches exactly once, so you get all 2**n subsets with no recursion. The cost is O(n × 2**n), fine for n up to about 20.

Bitmasks also compress "which items have I used?" into one integer, which makes them handy as dict keys and in dynamic programming over subsets.

Step by step

  1. Write in binary:

    a = 12 = 1100, b = 10 = 1010. Line them up by place value: 8, 4, 2, 1.

  2. AND:

    Column by column, 1 only where both are 1: 1000 = 8.

  3. OR:

    1 where either is 1: 1110 = 14.

  4. XOR:

    1 where they differ: 0110 = 6. Note a ^ b ^ b = a: XOR undoes itself.

  5. Shift:

    12 << 1 = 11000 = 24 (doubles). 12 >> 1 = 110 = 6 (halves, rounding down).

  6. x & (x - 1):

    12 - 1 = 11 = 1011. 1100 & 1011 = 1000 = 8: the lowest 1 bit disappeared. Repeat: 8 & 7 = 0. Two steps, so 12 has two 1 bits.

Code example

a, b = 12, 10
show = lambda x: format(x, "08b")
print("a      ", show(a), a)
print("b      ", show(b), b)
print("a & b  ", show(a & b), a & b)
print("a | b  ", show(a | b), a | b)
print("a ^ b  ", show(a ^ b), a ^ b)
print("a << 1 ", show(a << 1), a << 1)
print("a >> 1 ", show(a >> 1), a >> 1)

x, steps = 13, 0
while x:
    print("  clear lowest 1:", show(x), "->", show(x & (x - 1)))
    x &= x - 1
    steps += 1
print("13 has", steps, "one bits")

acc = 0
for v in [4, 1, 2, 1, 2]:
    acc ^= v
print("single number:", acc)

items = ["a", "b", "c"]
print([[items[i] for i in range(3) if (m >> i) & 1] for m in range(1 << 3)])

Complexity

  • Time: Each bit operation is O(1). Counting ones with x & (x - 1) is O(number of 1 bits). All subsets: O(n × 2^n).
  • Space: O(1) for the tricks. The subsets output itself is O(n × 2^n).

Interview tips

  • When you use a bit trick, explain it in plain words ('x & (x - 1) clears the lowest set bit') and show it on a small binary example. Unexplained tricks look memorised.

  • Mention language differences: Python ints are unbounded; Java/C++ ints are fixed width and right shift on negatives depends on the operator (>> vs >>>).

  • For 'single number', compare the hash-map solution (O(n) space) to XOR (O(1) space) to show you understand the trade-off.

  • Use bitmask enumeration only for small n and say so: 2^20 is about a million, 2^40 is not feasible.

Challenge: Subsets with a Bitmask

Return all subsets of nums using bitmasks. Use this exact order:

  • subsets in mask order 0, 1, 2, ..., 2**n - 1
  • bit i of the mask set means nums[i] is in the subset
  • inside a subset, items appear in their original order

Example: subsets_bitmask([1, 2]) → [[], [1], [2], [1, 2]]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Strings, Bits & Patterns

Previous: Knapsack, Subset Sum & Coin Change · Next: Pattern Matching: KMP & Rabin-Karp