Bit Manipulation Basics
How a Java int is stored as bits, the operators that work on those bits, and the few tricks most bit problems are built on.
Picture a number as a row of light switches, each one either off (0) or on (1). Bit manipulation means flipping, comparing and sliding those switches directly instead of doing ordinary arithmetic. It solves problems such as "which value has no partner?" or "how many switches are on?" with a few variables and no extra lists. All the examples use the same two numbers, 12 and 10.
Positions and place values
How does a computer write 12? In base 2, with only the digits 0 and 1. Each digit is called a bit, and each bit has a position, counted from 0 on the right. The bit at position 0 is worth 1, position 1 is worth 2, position 2 is worth 4 and position 3 is worth 8. Every step to the left doubles the worth.
12 is 8 + 4, so its bits at positions 3 and 2 are on and the rest are off. Written with eight positions, 12 is 0000 11000000 1010
A Java intlong
AND, OR and XOR, column by column
The three main operators compare two numbers one position at a time. Each position of the result depends only on the two bits in that same column. Here is 12, named ab
Start with the orange column, position 3. Both aba & b (AND)
The row labelled a | b (OR)
The row labelled a ^ b (XOR)
A fourth operator, ~~a0000 11001111 0011
Two shift operators slide all the bits sideways. The left shift a << 10001 1000a >> 20000 0011
Negative numbers in two's complement
Why is ~12int
To get -12 from 12, flip all the bits and then add 1. Flipping gives -13, and adding 1 gives -12, which in 32 bits is 1111 1111 1111 1111 1111 1111 1111 0100
Two things follow for the shift operators. The right shift >>-12 >> 1>>>-12 >>> 1int>>>
Shifting the other way can reach the sign bit too. 1 << 31intInteger.MIN_VALUE
Reading and changing one bit
How do you look at just one switch, say position 2 of a(a >> 2) & 1& 1
To change one bit, build a number that has a 1 only at that position, called a mask. 1 << k
- Turn bit 0 on with OR:
givesa | (1 << 0) , which is 13.0000 1101 - Turn bit 2 off with AND and the flipped mask:
keeps everything except position 2, giving 8.a & ~(1 << 2) - Flip bit 3 with XOR:
turns the 8 off, giving 4.a ^ (1 << 3)
Reading a bit and these three changes work the same way for any position from 0 to 31, and with 1L << klong
The lowest 1 bit: x & (x - 1) and x & -x
Two short expressions act on the rightmost bit that is on. In 12 that bit sits at position 2, marked orange here:
Look at the top three rows. Subtracting 1 from 12 borrows from position 2: that bit turns off, and the 0s below it, at positions 1 and 0, turn on. Everything to the left of the orange column stays the same. So a & (a - 1)x & (x - 1)x
Now the bottom three rows. In two's complement, -a-aaaa & -a
One direct use: a power of two, such as 8, has exactly one bit on, so clearing its lowest 1 bit leaves 0. The check x > 0 && (x & (x - 1)) == 0x > 0
Counting 1 bits: by position or by clearing
How many bits of 12 are on? The plain way checks all 32 positions with (x >> k) & 1
Clearing the lowest 1 bit gives a shorter loop: repeat x &= x - 1x
Java has this built in as Integer.bitCount(x)Long.bitCountlongInteger.MIN_VALUE
XOR cancels pairs
XOR has one property worth remembering: a number XOR-ed with itself gives 0, and XOR-ing with 0 changes nothing. So if a value goes in twice, the second time undoes the first. Take the list [12, 10, 12]result
The first row labelled "^ 12 gives" turns positions 3 and 2 on. The row labelled "^ 10 gives" flips positions 3 and 1, which leaves 6. In the last row, the second 12 flips positions 3 and 2 again, marked orange. The two 12s have cancelled, and 10, the value without a partner, is what remains.
The order does not matter, because a position flipped an even number of times ends at 0. Without XOR, the usual way to find the value without a partner is a hash map from each value to how often it appears, which needs memory for every distinct value. XOR needs one variable.
A number as a small set
Read the switches as "is item k in the set?" and an int
- Union:
is {1, 2, 3}, which is 14.a | b - Shared items:
is {3}, which is 8. When this is 0, the sets have nothing in common.a & b - Difference:
is what is ina & ~b but not ina , {2}.b - Size:
is 2.Integer.bitCount(a)
Sets stored this way are called bitmasks. To list every subset of n items, count mask(1 << n) - 1
The toolkit as one Java program
Everything so far fits in one class. The helper showcountEveryPositioncountOnescountByRemainder% 2/ 2isPowerOfTwounpairedmembers
The mainInteger.MIN_VALUEcountByRemainderisPowerOfTwoNoSignCheckx > 0
public class BitBasics {
// The lowest 8 bits of x as text, position 7 on the left and position 0 on the right.
static String bits8(int x) {
String s = Integer.toBinaryString(x & 0xFF);
s = "0".repeat(8 - s.length()) + s;
return s.substring(0, 4) + " " + s.substring(4);
}
static void show(String label, int value) {
System.out.printf("%-12s %s = %d%n", label, bits8(value), value);
}
// One bit at a time: look at all 32 positions.
static int countEveryPosition(int x) {
int count = 0;
for (int k = 0; k < 32; k++) {
count += (x >> k) & 1;
}
return count;
}
// One 1 at a time: each round of x & (x - 1) clears the lowest 1 bit.
static int countOnes(int x) {
int rounds = 0;
while (x != 0) {
x &= x - 1;
rounds++;
}
return rounds;
}
// Counts with remainders, the way you would on paper. Wrong for negative x.
static int countByRemainder(int x) {
int count = 0;
while (x != 0) {
count += x % 2;
x /= 2;
}
return count;
}
// The same check without x > 0.
static boolean isPowerOfTwoNoSignCheck(int x) {
return (x & (x - 1)) == 0;
}
static boolean isPowerOfTwo(int x) {
return x > 0 && (x & (x - 1)) == 0;
}
// Every value appears twice except one; XOR of all of them leaves that one.
static int unpaired(int[] nums) {
int result = 0;
for (int v : nums) {
result ^= v;
}
return result;
}
// The positions whose bit is 1, lowest first.
static String members(int mask) {
StringBuilder sb = new StringBuilder("{");
for (int k = 0; k < 32; k++) {
if (((mask >> k) & 1) == 1) {
sb.append(sb.length() > 1 ? ", " : "").append(k);
}
}
return sb.append("}").toString();
}
public static void main(String[] args) {
int a = 12;
int b = 10;
System.out.println("-- operators --");
show("a", a);
show("b", b);
show("a & b", a & b);
show("a | b", a | b);
show("a ^ b", a ^ b);
show("~a", ~a);
show("a << 1", a << 1);
show("a >> 2", a >> 2);
System.out.println("-- one bit of a --");
System.out.println("bit 2 of a: " + ((a >> 2) & 1) + ", bit 0 of a: " + ((a >> 0) & 1));
show("set bit 0", a | (1 << 0));
show("clear bit 2", a & ~(1 << 2));
show("flip bit 3", a ^ (1 << 3));
System.out.println("-- lowest 1 bit of a --");
show("-a", -a);
show("a - 1", a - 1);
show("a & (a - 1)", a & (a - 1));
show("a & -a", a & -a);
System.out.println("power of two? 12: " + isPowerOfTwo(12) + ", 8: " + isPowerOfTwo(8)
+ ", 0: " + isPowerOfTwo(0) + ", MIN_VALUE: " + isPowerOfTwo(Integer.MIN_VALUE));
System.out.println("-- counting 1 bits --");
int[] tests = {12, 0, -12, -1, Integer.MIN_VALUE};
for (int x : tests) {
System.out.println(x + " -> every position: " + countEveryPosition(x)
+ ", x & (x - 1): " + countOnes(x) + ", bitCount: " + Integer.bitCount(x));
}
System.out.println("-- XOR cancels pairs --");
int[] nums = {12, 10, 12};
System.out.println("unpaired in [12, 10, 12]: " + unpaired(nums));
System.out.println("unpaired in [7, 3, 5, 3, 7]: " + unpaired(new int[] {7, 3, 5, 3, 7}));
System.out.println("unpaired in [-12, 4, 4]: " + unpaired(new int[] {-12, 4, 4}));
System.out.println("-- bitmasks as sets --");
System.out.println("a = " + members(a) + ", b = " + members(b));
System.out.println("a | b = " + members(a | b) + ", a & b = " + members(a & b)
+ ", a & ~b = " + members(a & ~b));
for (int mask = 0; mask < (1 << 3); mask++) {
System.out.print(members(mask) + (mask < 7 ? " " : "\n"));
}
System.out.println("-- negative numbers and shifts --");
System.out.println("-12 in 32 bits: " + Integer.toBinaryString(-12));
System.out.println("-12 >> 1 = " + (-12 >> 1) + ", -12 >>> 1 = " + (-12 >>> 1));
System.out.println("-1 >> 1 = " + (-1 >> 1) + ", -1 >>> 1 = " + (-1 >>> 1));
System.out.println("1 << 31 = " + (1 << 31) + ", 1 << 32 = " + (1 << 32)
+ ", 1L << 32 = " + (1L << 32));
System.out.println("-- traps --");
System.out.println("countByRemainder(12) = " + countByRemainder(12)
+ ", countByRemainder(-12) = " + countByRemainder(-12));
System.out.println("without x > 0: 0 -> " + isPowerOfTwoNoSignCheck(0)
+ ", MIN_VALUE -> " + isPowerOfTwoNoSignCheck(Integer.MIN_VALUE));
}
}
Running it prints:
-- operators --
a 0000 1100 = 12
b 0000 1010 = 10
a & b 0000 1000 = 8
a | b 0000 1110 = 14
a ^ b 0000 0110 = 6
~a 1111 0011 = -13
a << 1 0001 1000 = 24
a >> 2 0000 0011 = 3
-- one bit of a --
bit 2 of a: 1, bit 0 of a: 0
set bit 0 0000 1101 = 13
clear bit 2 0000 1000 = 8
flip bit 3 0000 0100 = 4
-- lowest 1 bit of a --
-a 1111 0100 = -12
a - 1 0000 1011 = 11
a & (a - 1) 0000 1000 = 8
a & -a 0000 0100 = 4
power of two? 12: false, 8: true, 0: false, MIN_VALUE: false
-- counting 1 bits --
12 -> every position: 2, x & (x - 1): 2, bitCount: 2
0 -> every position: 0, x & (x - 1): 0, bitCount: 0
-12 -> every position: 29, x & (x - 1): 29, bitCount: 29
-1 -> every position: 32, x & (x - 1): 32, bitCount: 32
-2147483648 -> every position: 1, x & (x - 1): 1, bitCount: 1
-- XOR cancels pairs --
unpaired in [12, 10, 12]: 10
unpaired in [7, 3, 5, 3, 7]: 5
unpaired in [-12, 4, 4]: -12
-- bitmasks as sets --
a = {2, 3}, b = {1, 3}
a | b = {1, 2, 3}, a & b = {3}, a & ~b = {2}
{} {0} {1} {0, 1} {2} {0, 2} {1, 2} {0, 1, 2}
-- negative numbers and shifts --
-12 in 32 bits: 11111111111111111111111111110100
-12 >> 1 = -6, -12 >>> 1 = 2147483642
-1 >> 1 = -1, -1 >>> 1 = 2147483647
1 << 31 = -2147483648, 1 << 32 = 1, 1L << 32 = 4294967296
-- traps --
countByRemainder(12) = 2, countByRemainder(-12) = -2
without x > 0: 0 -> true, MIN_VALUE -> true
The block under "-- operators --" repeats the first picture: a & b0000 1000 = 8~a1111 0011 = -13a & (a - 1)a & -a
In the counting block, all three counts agree on every input. Look at the line for -12: 29 bits are on, because two's complement turned positions 4 to 31 on and position 2 stays on, while positions 3, 1 and 0 are off. For -1 the clearing loop needs all 32 rounds, the most it can ever take.
The XOR block finds 10 in [12, 10, 12][-12, 4, 4]mask
Traps worth knowing
What can go wrong? Five things, each seen in a run.
Paper arithmetic breaks on negative numbers. The line countByRemainder(-12) = -2&
A loop with >>-1 >> 1 = -1while (x != 0) x >>= 1;>>>
Shift distances wrap around. The line ending in 1 << 32 = 1int1L << k
Zero and the sign bit fool the power-of-two check. Without x > 0Integer.MIN_VALUEInteger.MIN_VALUE
Operator precedence. Java evaluates ==&^|
public class PrecedenceTrap {
public static void main(String[] args) {
int x = 12;
if (x & 1 == 0) {
System.out.println("even");
}
}
}
Running it does not get as far as printing anything:
src/PrecedenceTrap.java:4: error: bad operand types for binary operator '&'
if (x & 1 == 0) {
^
first type: int
second type: boolean
1 error
error: compilation failed
The "second type: boolean" line tells the story: Java read 1 == 0int(x & 1) == 0
Spotting a bit problem
Which problems call for bits? Look for these signs in the problem statement:
- The problem talks about the binary form of a number: count its 1 bits, reverse them, or compare two numbers bit by bit.
- Every value comes in pairs (or in threes) except one, and you must find the odd one out without extra memory. That is XOR, or a per-position count.
- You must decide whether a number is a power of two, or work with its lowest 1 bit.
- The items are few (26 letters, or up to about 20 choices) and you need to store or combine sets of them. A bitmask holds each set in one number.
- Arithmetic must be done without
,+ or* , which leaves the bit operators and shifts./
What these operations cost
How expensive is all this? One operator works on all 32 (or 64) bits at once, so a method's cost depends on how many operations it repeats:
- Time: O(1) for one
,& ,| ,^ or shift, and for every single-bit trick, because each is one operation on a fixed-size~ .int - Time: 32 steps for
on anycountEveryPosition , because it visits every position, whileint takes one round per bit that is on, two rounds for 12.countOnes - Time: O(n) and space O(1) for
on n values, because each value is XOR-ed once into a single variable. A hash map would also take O(n) time, but O(n) space.unpaired - Time: O(n ยท 2n) to list every subset of n items with
, because there are 2n masks and listing one means checking its n positions (themembers helper simply checks all 32).members
Where to go next
Problems where XOR cancels pairs:
Single Number is the idea on a full array.[12, 10, 12]Missing Number pairs each value with its index, so the one missing value is left over.
Problems that count 1 bits:
Number of 1 Bits is the counting loop on one number.Counting Bits counts for every number up to n, reusing the counts of smaller numbers.Hamming Distance XORs two numbers and counts the positions where they differ.
Problems built on the lowest 1 bit:
Power of Two is the check, with its edge cases.x & (x - 1)Single Number III has two unpaired values and uses to split them apart.x & -x
Problems that work one position at a time:
Single Number II has values in threes, so it counts each position instead of XOR-ing.Reverse Bits moves bits out of one end with shifts and into the other.
Problems that use bitmasks as sets:
Maximum Product of Word Lengths stores each word's letters as a 26-bit mask so two words share no letter exactly when their masks AND to 0.