Common bit tricks
A small set of one-line expressions covers most bit manipulation: test, set, clear and toggle a bit, isolate or remove the lowest set bit, check for a power of two, and count set bits. Each is a combination of a mask and one operator.
Learning goals
- Write the expressions to test, set, clear and toggle bit i
- Explain why n & (n - 1) removes the lowest set bit
- Check for a power of two correctly, including for 0 and negatives
- Count set bits in time proportional to the number of ones
Prerequisites
Test bit
To read bit i, shift it down to position 0 and mask with 1: (n >> i) & 1. Or build a mask with a single 1 at i and check for non-zero: (n & (1 << i)) != 0. Either works, and the second does not need the result to be exactly 1.
The widget lets you pick any of the tricks in this lesson, with n and i, and shows the intermediate rows. Choose “Test bit i” first.
1static boolean test(int n, int i) { return ((n >> i) & 1) == 1; }2static boolean test2(int n, int i) { return (n & (1 << i)) != 0; }
Bit tricks: test, set, clear, toggle, lowest set bit
Interactive · edit the inputn = 44
Test bit i on n = 44, i = 2. Bit 2 is counted from the right, starting at 0.
1boolean test(int n, int i) { return ((n >> i) & 1) == 1; }2int set(int n, int i) { return n | (1 << i); }3int clear(int n, int i) { return n & ~(1 << i); }4int toggle(int n, int i) { return n ^ (1 << i); }5int lowestSetBit(int n) { return n & -n; }6int removeLowestSetBit(int n) { return n & (n - 1); }7boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; }
Live state
n
44
i
2
Execution trace (dry run table)Show 4 stepsHide
| Step | Line | State | What happens |
|---|---|---|---|
| 1 | L1 | n=44 i=2 | Test bit i on n = 44, i = 2. Bit 2 is counted from the right, starting at 0. |
| 2 | L1 | n=44 i=2 mask=4 | Build a mask with a single 1 at position 2: 1 << 2 = 4. |
| 3 | L1 | shifted=11 | Shift n right by 2 so bit 2 lands at position 0, then AND with 1 to keep only that bit. |
| 4 | L1 | return=true | Bit 2 of 44 is 1, so test returns true. |
Set bit
To force bit i to 1, OR with a mask that has only bit i set: n | (1 << i). If the bit was already 1 nothing changes. In the widget, choose “Set bit i”.
To set several bits at once, OR with the combined mask: n | 0b1010.
1static int set(int n, int i) { return n | (1 << i); }
Clear bit
To force bit i to 0, AND with a mask that has every bit set except bit i: n & ~(1 << i). The ~ turns the single-bit mask into the inverse mask.
To clear the lowest k bits use n & ~((1 << k) - 1), or (n >> k) << k.
1static int clear(int n, int i) { return n & ~(1 << i); }
Toggle bit
To flip bit i, XOR with the single-bit mask: n ^ (1 << i). A 0 becomes 1 and a 1 becomes 0, and every other bit is unchanged. Applying it twice restores the original.
Toggling is how you flip light switches in a bitmask puzzle: each move is one XOR.
1static int toggle(int n, int i) { return n ^ (1 << i); }
Isolate lowest set bit
n & -n keeps only the lowest set bit of n. Because -n is ~n + 1, below the lowest set bit both n and -n are 0, at that bit both are 1, and above it they are complements, so the AND keeps just that one bit. For 44 (0010 1100) the result is 4.
This is the building block of Fenwick trees (Chapter 29), where i & -i is the step size, and it is used to iterate over set bits.
1static int lowestSetBit(int n) { return n & -n; } // 44 -> 4, 40 -> 8, 0 -> 02int index = Integer.numberOfTrailingZeros(n); // its position
Remove lowest set bit
n & (n - 1) clears the lowest set bit. Subtracting 1 turns the lowest 1 into 0 and every 0 below it into 1, so ANDing with n removes exactly that bit. For 44 (0010 1100) it gives 40 (0010 1000).
Repeating it until n is 0 visits each set bit once, which is Brian Kernighan's way to count bits.
1static int removeLowestSetBit(int n) { return n & (n - 1); } // 44 -> 40 -> 32 -> 0
Check power of two
A positive number is a power of two if it has exactly one set bit, which means removing the lowest set bit leaves 0: n > 0 && (n & (n - 1)) == 0. The n > 0 check is needed because 0 & -1 is also 0, and negative numbers are not powers of two.
Run “Is 64 a power of two?” and “Is 44 a power of two?” in the widget to see n - 1 and the AND result.
1static boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; }2// 64 -> true, 44 -> false, 1 -> true, 0 -> false, Integer.MIN_VALUE -> false
Count set bits
Brian Kernighan's algorithm counts set bits by clearing the lowest set bit until none are left: while (n != 0) { n &= n - 1; count++; }. It takes one iteration per set bit, not one per bit position. Step through 108 and then 255 to compare.
A simple loop that tests all 32 positions always takes 32 steps. In practice use Integer.bitCount, which the JIT compiles to a single CPU instruction (popcnt) on most hardware.
Worst
O(number of set bits)
Space
O(1)
Count set bits (Brian Kernighan)
Interactive · edit the inputn = 108
Count the 1 bits. The loop runs once per set bit, not once per bit position.
1static int popCount(int n) {2int count = 0;3while (n != 0) {4n &= n - 1; // clears the lowest set bit5count++;6}7return count;8}
Live state
n
108
count
0
Execution trace (dry run table)Show 15 stepsHide
| Step | Line | State | What happens |
|---|---|---|---|
| 1 | L2 | n=108 count=0 | Count the 1 bits. The loop runs once per set bit, not once per bit position. |
| 2 | L3 | n=108 count=0 | n still has a 1 bit. |
| 3 | L4 | n=108 n - 1=107 next=104 count=0 | n - 1 flips bit 2 (the lowest 1) and every bit below it. ANDing with n clears exactly that lowest 1. |
| 4 | L5 | n=104 count=1 | count = 1. |
| 5 | L3 | n=104 count=1 | n still has a 1 bit. |
| 6 | L4 | n=104 n - 1=103 next=96 count=1 | n - 1 flips bit 3 (the lowest 1) and every bit below it. ANDing with n clears exactly that lowest 1. |
| 7 | L5 | n=96 count=2 | count = 2. |
| 8 | L3 | n=96 count=2 | n still has a 1 bit. |
| 9 | L4 | n=96 n - 1=95 next=64 count=2 | n - 1 flips bit 5 (the lowest 1) and every bit below it. ANDing with n clears exactly that lowest 1. |
| 10 | L5 | n=64 count=3 | count = 3. |
| 11 | L3 | n=64 count=3 | n still has a 1 bit. |
| 12 | L4 | n=64 n - 1=63 next=0 count=3 | n - 1 flips bit 6 (the lowest 1) and every bit below it. ANDing with n clears exactly that lowest 1. |
| 13 | L5 | n=0 count=4 | count = 4. |
| 14 | L3 | n=0 count=4 | n is 0: no bits left. |
| 15 | L7 | return=4 | 108 has 4 set bits, found in 4 iterations (a plain loop over all 8 positions would take 8). |
Practice ladder
Now try it yourself
Easy
- Set the 3rd bit of a number
- Check if a number is even using &
- Is n a power of two?
Medium
- Count the number of bits to flip to convert a into b (Hamming distance)
- Find the position of the lowest set bit
- Check whether n is a power of four
Advanced
- Round up to the next power of two without a loop
- Count set bits for every number from 0 to n in O(n) using dp[i] = dp[i >> 1] + (i & 1)
- Reverse the order of the bits in an int
Key takeaways
- Test: (n >> i) & 1; set: n | (1 << i); clear: n & ~(1 << i); toggle: n ^ (1 << i).
- n & -n isolates the lowest set bit, n & (n - 1) removes it.
- Power of two: n > 0 && (n & (n - 1)) == 0; Kernighan counts bits in one step per set bit.