Skip to content
Visual explainer 3h to learn 5 steps

Bit manipulation

Use bitwise operators to test, set and count bits and represent sets as bitmasks.

By Invicly Tech, , in Data Structures & Algorithms. About 13 minutes to read.

Topic 47 of 54

In short

Integers are stored in binary, and bitwise operators let you read and change individual bits in O(1). Bit tricks test powers of two, count set bits and find a unique element with XOR. A bitmask can represent a subset of up to about 20 to 30 items, enabling compact DP and enumeration.

Explained simply

Computers store every integer as a row of bits, which are 0s and 1s. The number 13 is 1101 in binary: 8 + 4 + 0 + 1. Each position is worth twice the one to its right. Bit manipulation means reading and changing those 0s and 1s directly.

There are a few operators. AND (&) keeps a bit only where both numbers have a 1. OR (|) keeps a bit where either has a 1. XOR (^) keeps a bit where exactly one has a 1. NOT (~) flips every bit. Shifts (<< and >>) slide all bits left or right, which multiplies or divides by powers of 2.

Why bother? These operations are among the fastest things a CPU can do. They also let one integer act as a tiny set: bit i is 1 if item i is in the set. Twenty items fit in one number, and checking membership is a single AND.

In Python there is one surprise: integers have no fixed size. They never overflow, and negative numbers behave as if they had infinitely many 1 bits on the left. That is handy, but it means some tricks from C or Java need a mask to work the same way.

Press Play on a diagram to walk through it one step at a time.

CompareEveryday bit operations
Test and set
  • Test bit i: x >> i & 1
  • Set bit i: x | (1 << i)
  • Clear bit i: x & ~(1 << i)
  • Toggle bit i: x ^ (1 << i)
Tricks
  • Lowest set bit: x & -x
  • Drop lowest bit: x & (x - 1)
  • Power of two: x > 0 and x & (x - 1) == 0
  • a ^ a == 0
ComparePython versus C and Java bits
Python
  • Integers never overflow
  • ~5 == -6, -5 >> 1 == -3
  • x & 1 == 0 is (x & 1) == 0
  • Mask with 0xFFFFFFFF for 32 bits
C and Java
  • Fixed 32 or 64 bits
  • Java: >>> is an unsigned shift
  • x & 1 == 0 is x & (1 == 0)
  • Overflow wraps or is undefined

In depth

Negative numbers and Python's endless bits

Computers store negative integers in two's complement: to negate x, flip all bits and add 1, so -x == ~x + 1. In an 8-bit world, 5 is 00000101 and -5 is 11111011. Python follows the same rules but with an unlimited number of bits, so -5 is "...11111011" with 1s forever to the left. That is why ~5 == -6 and why bin(-5) prints "-0b101" (a minus sign, not the raw bits).

To copy 32-bit behaviour, mask with & 0xFFFFFFFF, which keeps the low 32 bits as a non-negative number. To turn that back into a signed value, subtract 2^32 if the result is at least 2^31. Right shift on negatives rounds down: -5 >> 1 == -3, the same as -5 // 2.

  • -x == ~x + 1 and ~x == -x - 1
  • Low 32 bits: x & 0xFFFFFFFF
  • Back to signed: x - (1 << 32) if x >= 1 << 31
  • -5 >> 1 == -3 (floor)

The lowest set bit

Two expressions do most of the clever work. x & (x - 1) clears the lowest 1 bit. Subtracting 1 turns the lowest 1 into 0 and every 0 to its right into 1; ANDing with the original wipes all of those. For 12 (1100), x - 1 is 1011, and the AND is 1000, which is 8.

x & -x isolates the lowest 1 bit. In two's complement, -x flips every bit above the lowest 1 and keeps that bit itself, so only it survives the AND. For 12 that is 0100, which is 4. Fenwick trees are built on exactly this value.

Counting bits by repeatedly clearing the lowest one (Brian Kernighan's method) loops once per 1 bit, not once per bit position. In Python 3.10 and later, x.bit_count() returns the count directly, and x.bit_length() gives the number of bits needed to write x.

Flowx = 12 (1100)
  1. Step 1
    x - 1

    1011: lowest 1 becomes 0, zeros to its right become 1

  2. Step 2
    x & (x - 1)

    1000 = 8: lowest 1 cleared

  3. Step 3
    -x

    ...10100 in two's complement

  4. Step 4
    x & -x

    0100 = 4: lowest 1 isolated

XOR, the cancelling operator

XOR has three properties that power many tricks: a ^ a == 0, a ^ 0 == a, and the order does not matter. So XOR-ing a list cancels every value that appears an even number of times.

Missing number: the list holds 0 to n with one value missing. XOR every index 0 to n with every value; everything pairs up except the missing one. Two single numbers: when exactly two values appear once and all others twice, XOR everything to get x = a ^ b. Since a and b differ, x has at least one 1 bit; take it with x & -x. That bit splits the list into two groups, one holding a and the other b, and XOR-ing each group gives each answer. All of these are O(n) time and O(1) space.

XOR also detects which bits changed between two values: a ^ b has 1s exactly where they differ, so (a ^ b).bit_count() is their Hamming distance.

Bitmasks as small sets

With n items, any subset is an integer from 0 to 2^n - 1. Set operations become single instructions: union a | b, intersection a & b, difference a & ~b, add item i with mask | 1 << i, and test it with mask >> i & 1.

To visit every submask of a mask, use sub = (sub - 1) & mask, starting from mask and stopping after 0. Doing that for every mask of n bits costs 3^n in total, because each item is either outside the mask, in the mask but not the submask, or in both.

Bitmask DP uses the mask as part of the state. The travelling salesperson problem with Held-Karp DP has states (visited set, current city): 2^n x n states with n transitions each, O(2^n x n^2). That is about 400 million steps for n = 20, which is slow in Python but standard in C++.

  • Every subset: for mask in range(1 << n)
  • Every submask: sub = (sub - 1) & mask
  • All submasks of all masks: 3^n total
FlowSubmasks of 101 (items 0 and 2)
  1. Step 1
    sub = 101

    Both items

  2. Step 2
    (101 - 1) & 101

    100 & 101 = 100: item 2

  3. Step 3
    (100 - 1) & 101

    011 & 101 = 001: item 0

  4. Step 4
    (001 - 1) & 101

    000: empty set, stop after it

Precedence traps

Python's operator priority, from tighter to looser, goes: unary ~ and -, then * and /, then + and -, then << and >>, then &, then ^, then |, then comparisons like ==. So 1 << n - 1 means 1 << (n - 1), and x & 1 == 0 means (x & 1) == 0 in Python.

That last one is a trap when you move to C, C++ or Java, where == binds tighter than &, so x & 1 == 0 means x & (1 == 0). Parentheses cost nothing and make code portable, so write (x & 1) == 0 anyway.

Shifts in Python never overflow: 1 << 100 is a valid 101-bit integer. In C, shifting a 32-bit int by 32 or more is undefined behaviour, and in Java the shift amount is taken modulo 32 for int, so 1 << 32 == 1.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Use AND, OR, XOR, NOT and shifts~35m
  2. 2
    Test, set and clear individual bits~35m
  3. 3
    Count bits and isolate the lowest bit~35m
  4. 4
    Find the single number with XOR~35m
  5. 5
    Enumerate subsets with bitmasks~35m

Key points

  • Bitwise operations are O(1) on machine-sized integers.
  • XOR of all numbers cancels pairs, leaving the single number in O(n).
  • Enumerating all masks of n items is O(2^n).
  • Python ints are unbounded, so negative numbers behave like infinite two's complement.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
from functools import reduce
from operator import xor

print(reduce(xor, [4, 1, 2, 1, 2]))   # 4: pairs cancel
print(bin(13), (13).bit_count())      # 0b1101 3

def is_power_of_two(x):
    return x > 0 and x & (x - 1) == 0

items = ['a', 'b', 'c']
for mask in range(1 << len(items)):   # all 8 subsets
    print([items[i] for i in range(len(items)) if mask >> i & 1])

Two numbers that appear once

In [1, 2, 1, 3, 2, 5], every value appears twice except 3 and 5. Step 1: XOR everything: the pairs cancel and x = 3 ^ 5 = 6 (110). Step 2: the lowest set bit of 6 is 2 (010); 3 has that bit and 5 does not. Step 3: XOR the numbers with that bit (2, 3, 2 gives 3) and those without it (1, 1, 5 gives 5). Answer: 3 and 5. One extra pass, no extra memory.

python
from functools import reduce
from operator import xor

def two_singles(nums):
    x = reduce(xor, nums)          # a ^ b
    bit = x & -x                   # a bit where a and b differ
    a = 0
    for v in nums:
        if v & bit:
            a ^= v                 # group that contains one of them
    return sorted((a, x ^ a))

print(two_singles([1, 2, 1, 3, 2, 5]))  # [3, 5]

Words with no shared letters

Find the largest product of lengths of two words that share no letters. Step 1: turn each word into a 26-bit mask, with bit i set if letter i appears. "abcw" gets bits for a, b, c and w. Step 2: two words share no letter exactly when their masks AND to 0, one fast operation instead of comparing letters. For ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"], the best pair is "abcw" and "xtfn": 4 x 4 = 16.

python
def max_product(words):
    masks = []
    for w in words:
        m = 0
        for ch in w:
            m |= 1 << (ord(ch) - ord("a"))
        masks.append(m)
    best = 0
    for i in range(len(words)):
        for j in range(i + 1, len(words)):
            if masks[i] & masks[j] == 0:
                best = max(best, len(words[i]) * len(words[j]))
    return best

print(max_product(["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]))  # 16

Quick reference

  • Test bit i: x >> i & 1; set: x | 1 << i; clear: x & ~(1 << i); flip: x ^ 1 << i
  • x & (x - 1) clears the lowest 1 bit; x & -x keeps only the lowest 1 bit
  • x.bit_count() counts 1 bits (Python 3.10+); x.bit_length() counts digits
  • XOR of a list cancels pairs: a ^ a == 0, a ^ 0 == a
  • Every submask: sub = (sub - 1) & mask until 0; all masks together cost 3^n
  • Python ~x == -x - 1; emulate 32 bits with & 0xFFFFFFFF
  • In C and Java, write (x & 1) == 0 with parentheses
  • Power of two: x > 0 and x & (x - 1) == 0

Common mistakes

  • Operator precedence: in Python, & binds tighter than == but looser than + and <<.
  • Expecting fixed 32-bit overflow behaviour in Python.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is 22 & -22? (22 is 10110 in binary.)

Question 2

2What does Python print for ~7?

Question 3

3How many submask steps does enumerating every submask of every mask of n bits take in total?

Question 4

4In Java, what does x & 1 == 0 compute?

Question 5

5nums holds every number from 0 to n except one. Which XOR finds the missing one?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Return a list where entry i is the number of 1 bits in i, for i from 0 to n, in O(n). Example: n = 5 gives [0, 1, 1, 2, 1, 2].

  2. Exercise 2medium

    Every number appears three times except one, which appears once. Values are signed 32-bit integers. Find the single one in O(n) time and O(1) space. Example: [0, 1, 0, 1, 0, 1, -99] gives -99.

  3. Exercise 3hard

    Solve the travelling salesperson problem for a small distance matrix with bitmask DP: start at city 0, visit every city once, return to 0. The 4-city example below gives 80.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Are bitwise operations faster than normal arithmetic in Python?
Not by much for single operations, because the interpreter overhead dominates. The real wins are packing many booleans into one integer and replacing loops with a few whole-mask operations.
How do I print a number in binary with leading zeros?
Use format(x, "08b") or f"{x:08b}" for 8 digits. For negative numbers, mask first, for example format(x & 0xFF, "08b").
Why does Python show negative numbers in binary with a minus sign?
Python integers have no fixed width, so there is no natural number of leading 1 bits to print. bin() shows the sign and the size instead; mask with a width like 0xFFFFFFFF to see the two's complement bits.
How many items can a bitmask hold?
In Python, any number, because integers are unbounded. Algorithms that loop over all masks are limited by 2^n, so around 20 to 25 items is the practical ceiling.

Go deeper

ShareXLinkedInWhatsApp