Bit Manipulation
How to test, set and clear single bits, count bits, find a lone value with XOR and list subsets with masks, plus what interviewers ask about bits.
On this page
- Binary numbers and the bit operators
- Testing, setting and clearing one bit with a mask
- Counting the 1 bits with x & (x − 1)
- Finding the value without a partner with XOR
- Representing subsets as masks
- Variants of the XOR and mask techniques
- Pitfalls in JavaScript and Python
- In the interview
- What to practise next
Bit manipulation means working directly on the binary digits of an integer with operators such as AND, OR, XOR and shifts. It is used to store many yes/no flags in one number, to do some jobs in constant extra memory that would otherwise need a hash map or a loop, and to represent a subset of a small set as a single integer. You reach for it when a problem asks about flags, parity, a value that appears an odd number of times, or all subsets of at most about 20 items.
Without it, a set of six on/off settings needs six separate booleans, and "find the one number without a partner" needs a hash map that uses O(n) memory. With bits, the six settings fit in one integer that can be copied or compared in one operation, and the lone number can be found with O(1) memory.
Binary numbers and the bit operators
In binary, each position is worth twice the position to its right: 1, 2, 4, 8, 16, 32. A number is the sum of the positions that hold a 1. Positions are numbered from the right starting at 0, so in 44 the bits at positions 2, 3 and 5 are on.
The bitwise operators work on every bit position at the same time. AND gives a 1 only where both numbers have a 1, OR gives a 1 where either number has one, and XOR gives a 1 where the two numbers differ. NOT flips every bit. A left shift by k moves all bits k places to the left, which multiplies the number by 2ᵏ, and a right shift by k moves them right and drops the lowest k bits, which divides by 2ᵏ and rounds down.
| Operator | Example |
|---|---|
a & b (AND) | 1100 & 1010 = 1000, so 12 & 10 is 8 |
a | b (OR) | 1100 | 1010 = 1110, so 12 | 10 is 14 |
a ^ b (XOR) | 1100 ^ 1010 = 0110, so 12 ^ 10 is 6 |
~a (NOT) | ~5 is −6 |
a << k | 12 << 1 is 24 |
a >> k | 12 >> 2 is 3 |
Testing, setting and clearing one bit with a mask
To change one bit without touching the others, you build a mask that has a 1 only at that position. The expression 1 << i produces it. You then combine the mask with the number using one of four operations.
- Check bit i:
(x >> i) & 1moves bit i to the lowest position and keeps only that bit, so the result is 1 if the bit is on. - Set bit i:
x | (1 << i). OR with a 1 always produces a 1, and OR with the 0s of the mask leaves the other bits as they were. - Clear bit i:
x & ~(1 << i). The flipped mask has a 0 only at position i, and AND with 0 always produces 0, while AND with the 1s leaves the other bits as they were. - Toggle bit i:
x ^ (1 << i). XOR with a 1 flips a bit, and XOR with a 0 leaves it alone.
The example below stores six camera settings in one number, with the grid-lines setting at bit 0, flash at bit 1 and timer at bit 2.
const isOn = (x, i) => ((x >> i) & 1) === 1;
const turnOn = (x, i) => x | (1 << i);
const turnOff = (x, i) => x & ~(1 << i);
const flip = (x, i) => x ^ (1 << i);
let settings = 0; // all six off
settings = turnOn(settings, 1); // flash: 000010
settings = turnOn(settings, 2); // timer: 000110, which is 6
isOn(settings, 2); // true
settings = flip(settings, 1); // flash off again: 000100, which is 4def is_on(x, i):
return ((x >> i) & 1) == 1
def turn_on(x, i):
return x | (1 << i)
def turn_off(x, i):
return x & ~(1 << i)
def flip(x, i):
return x ^ (1 << i)
settings = 0 # all six off
settings = turn_on(settings, 1) # flash: 000010
settings = turn_on(settings, 2) # timer: 000110, which is 6
is_on(settings, 2) # True
settings = flip(settings, 1) # flash off again: 000100, which is 4Each operation is a single instruction on one machine word.
Counting the 1 bits with x & (x − 1)
The expression x & (x - 1) turns off the lowest 1 bit of x and leaves every other bit unchanged. Subtracting 1 turns the lowest 1 into a 0 and turns every 0 below it into a 1, while the bits above it do not change. AND with the original number then keeps only the bits that were 1 in both, and the only bits that differ between x and x − 1 are the lowest 1 and the ones below it, so exactly the lowest 1 disappears.
Repeating this until x is 0 counts the 1 bits, and the number of repetitions equals the number of 1 bits. The tracer below does it for 44.
count = 0while x != 0: x = x & (x - 1) # drop the lowest 1 count += 132 16 8 4 2 1 x = 44 1 0 1 1 0 0 - x
- 44
- count
- 0
1x = 44 is 101100, and the count starts at 0. The loop will drop one 1 bit per round instead of checking every position.
32 16 8 4 2 1 x = 44 1 0 1 1 0 0 x − 1 = 43 1 0 1 0 1 1 - x
- 44
- count
- 0
2Subtracting 1 gives 43, which is 101011. The lowest 1, worth 4, became 0 and the zeros below it became 1s. Nothing above it changed.
32 16 8 4 2 1 x = 44 1 0 1 1 0 0 x − 1 = 43 1 0 1 0 1 1 x & (x − 1) = 40 1 0 1 0 0 0 - x
- 40
- count
- 1
3AND keeps a bit only where both rows have a 1. The rows differ only at and below the lowest 1, so exactly that bit disappears and x becomes 40.
32 16 8 4 2 1 x = 40 1 0 1 0 0 0 x − 1 = 39 1 0 0 1 1 1 - x
- 40
- count
- 1
4Subtracting 1 from 40 gives 39, which is 100111. The lowest 1, worth 8, became 0 and everything below it became 1.
32 16 8 4 2 1 x = 40 1 0 1 0 0 0 x − 1 = 39 1 0 0 1 1 1 x & (x − 1) = 32 1 0 0 0 0 0 - x
- 32
- count
- 2
5AND leaves 32 and the count becomes 2.
32 16 8 4 2 1 x = 32 1 0 0 0 0 0 x − 1 = 31 0 1 1 1 1 1 - x
- 32
- count
- 2
6Now x = 32 has a single 1 bit, and subtracting 1 gives 31, which is 011111.
32 16 8 4 2 1 x = 32 1 0 0 0 0 0 x − 1 = 31 0 1 1 1 1 1 x & (x − 1) = 0 0 0 0 0 0 0 - x
- 0
- count
- 3
7AND gives 0, so the loop stops with a count of 3. It ran three times because 44 has three 1 bits, not once for each of the six positions.
The same expression tests for a power of two, because a power of two has exactly one 1 bit and dropping it leaves 0. The test also needs x > 0, since 0 would otherwise pass.
function countOnes(x) {
let count = 0;
while (x !== 0) {
x &= x - 1; // drop the lowest 1
count++;
}
return count;
}
const isPowerOfTwo = (x) => x > 0 && (x & (x - 1)) === 0;
countOnes(44); // 3
isPowerOfTwo(32); // true
isPowerOfTwo(44); // falsedef count_ones(x):
count = 0
while x != 0:
x &= x - 1 # drop the lowest 1
count += 1
return count
def is_power_of_two(x):
return x > 0 and (x & (x - 1)) == 0
count_ones(44) # 3
is_power_of_two(32) # True
is_power_of_two(44) # Falsek is the number of 1 bits in x, so the loop runs at most as many times as x has bits.
Python 3.10 and later has x.bit_count(), which does the same count.
Finding the value without a partner with XOR
XOR has three properties that matter here: a number XOR itself is 0, a number XOR 0 is the number itself, and the order of the operands does not matter. If you XOR every value in a list in which each value appears twice except one, every pair cancels to 0 and only the single value remains. This needs no hash map, so the memory is constant.
For [4, 7, 2, 7, 4] the running result is 4, then 4 ^ 7 = 3, then 3 ^ 2 = 1, then 1 ^ 7 = 6, then 6 ^ 4 = 2.
function unpaired(ids) {
let result = 0;
for (const id of ids) result ^= id; // pairs cancel out
return result;
}
unpaired([4, 7, 2, 7, 4]); // 2def unpaired(ids):
result = 0
for sock_id in ids:
result ^= sock_id # pairs cancel out
return result
unpaired([4, 7, 2, 7, 4]) # 2One pass over the list with a single running value.
Representing subsets as masks
A subset of n items can be stored as an n-bit number in which bit i is 1 when item i is in the subset. For the three items C, E and T, the mask 5 is 101, which means bits 0 and 2 are on, so the subset is C and T. Counting the mask from 0 to 2ⁿ − 1 visits every subset exactly once, and no recursion is needed. This is an alternative to the recursive approach in Backtracking.
function subsetsByMask(items) {
const result = [];
for (let mask = 0; mask < (1 << items.length); mask++) {
const subset = [];
for (let i = 0; i < items.length; i++) {
if ((mask >> i) & 1) subset.push(items[i]); // bit i on: take item i
}
result.push(subset);
}
return result;
}
subsetsByMask(["C", "E", "T"])[5]; // ["C", "T"]def subsets_by_mask(items):
result = []
for mask in range(1 << len(items)):
subset = [items[i] for i in range(len(items)) if (mask >> i) & 1]
result.append(subset)
return result
subsets_by_mask(["C", "E", "T"])[5] # ['C', 'T']There are 2ⁿ masks and each one needs n bit checks. The space does not count the output.
Variants of the XOR and mask techniques
Missing number
If a list holds the numbers 0 to n with one number missing, XOR all the list values together with all the indexes 0 to n. Every number that is present appears once as a value and once as an index, so it cancels, and the missing number appears only as an index and is left over.
Two values without a partner
If two different values appear once and all others appear twice, XOR of everything gives a ^ b, which is not 0 because a and b differ. Pick any bit that is 1 in a ^ b, for example the lowest one, d = x & -x. That bit is 1 in one of the two values and 0 in the other, so you can split the list into two groups by that bit, and XOR each group separately to get a and b. Each group contains one lone value and some complete pairs.
A value that appears three times
If every value appears three times except one that appears once, plain XOR does not work, because three equal values XOR to the value itself and not to 0. The usual solution counts, for each bit position, how many numbers have that bit on and takes that count modulo 3. The remaining bits form the lone value. This takes O(32 · n) time and O(1) space.
The lowest 1 bit and two's complement
The expression x & -x keeps only the lowest 1 bit of x. Computers store a negative number as its two's complement, which is the bits of the number flipped, plus 1. Flipping turns the lowest 1 into a 0 with 1s below it, and adding 1 carries back up to exactly that position, so -x matches x at the lowest 1 and is the opposite of x everywhere above it. For 44, which is 101100, x & -x is 4. Fenwick trees use this form.
When bits do not apply
Bit tricks do not help when the values are not integers, when you need to know which items form a pair and not just the lone value, or when the set has more than about 20 items. A subset mask needs 2ⁿ iterations, so it is only practical for n up to roughly 20, and a hash map or a sorted list is simpler for most other counting problems.
Pitfalls in JavaScript and Python
In the interview
The signals in the problem statement are the words "without extra space", "every element appears twice except one", "power of two", "number of 1 bits" or "set bits", "flags" or "permissions", and "all subsets" with a small n. A constraint of n at most about 20 often means a bitmask is intended. Say that you considered the hash-map or sorting solution first and what the bit version saves.
Questions to expect:
- "Can you do it without extra memory?" For a lone value among pairs, XOR all the elements. The pairs cancel, so one integer of memory is enough, and the time is O(n).
- "How do you check whether a number is a power of two?" A power of two has exactly one 1 bit, so
x > 0 && (x & (x - 1)) === 0works. Thex > 0part is needed because 0 would otherwise pass. - "How do you count the 1 bits faster than checking every position?" Repeat
x &= x - 1until x is 0. It runs once per 1 bit. - "Two numbers appear once and the rest appear twice. Find both." XOR everything to get a ^ b, pick a bit that is set in that result, and split the list by that bit. XOR each group separately, and each group yields one of the two numbers.
- "What about negative numbers?" Say which language and width you are assuming. JavaScript uses 32-bit signed integers, Python integers are unbounded and need a mask, and in both languages a right shift of a negative number keeps the sign, so use an unsigned shift or a mask.
- "When would you use bits instead of a set or a boolean array?" Use bits when the universe is small and fixed, for example at most 20 to 30 items, because the whole state fits in one integer that can be used as a key in a dynamic programming table. For a larger universe, a boolean array or a hash set is clearer.
What is 13 & 6?
Why does isPowerOfTwo check x > 0 as well as (x & (x - 1)) === 0?
What do you get by XOR-ing all of [9, 3, 9, 5, 3]?
Every number in a list appears three times except one that appears once. Why does XOR-ing the whole list fail to find the single number?
What to practise next
Bit masks come back in harder dynamic programming problems, where a mask records which items have been used, and the lowest-bit trick is the core of Fenwick trees.