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 1100. The other running number, 10, is 8 + 2, so it is 0000 1010.

A Java int has 32 positions, numbered 0 to 31, and a long has 64. For 12 and 10, positions 4 to 31 are all 0, so the pictures below show only the lowest eight.

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 a, and 10, named b, with the three results below the line:

a = 12 is 0000 1100 and b = 10 is 0000 1010. a AND b = 0000 1000 = 8, a OR b = 0000 1110 = 14, a XOR b = 0000 0110 = 6. Position 3 is 1 in both and is highlighted.

Start with the orange column, position 3. Both a and b have a 1 there. The row labelled a & b (AND) has a 1 in a column only when both numbers do, so it keeps position 3 and nothing else: 8.

The row labelled a | b (OR) has a 1 wherever at least one of the numbers has one. That is positions 3, 2 and 1, which makes 8 + 4 + 2 = 14.

The row labelled a ^ b (XOR) has a 1 where the two bits differ. Position 3 holds 1 in both, so XOR drops it. Positions 2 and 1 differ, so the result is 4 + 2 = 6. The name XOR means "exclusive or": one of the two, but not both.

A fourth operator, ~ (NOT), flips all 32 bits of one number. ~a turns the low eight bits 0000 1100 into 1111 0011, and every higher position becomes 1 too. Java prints that as -13.

Two shift operators slide all the bits sideways. The left shift a << 1 moves every bit one position left and puts a 0 in position 0, giving 0001 1000, which is 24. That doubles the number. The right shift a >> 2 moves the bits two positions right, and the two lowest bits fall off the end: 0000 0011, which is 3, the same as 12 divided by 4.

Negative numbers in two's complement

Why is ~12 equal to -13? A Java int uses position 31, the leftmost of its 32 positions, as a sign: when it is 1, the number is negative. Flipping all the bits of 12 turned position 31 on, so the result is negative.

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. This way of storing negative values is called two's complement. Its advantage is that plain addition needs no special case: adding 12 to -12 carries off the left end and leaves 0.

Two things follow for the shift operators. The right shift >> copies the sign bit into the empty positions on the left, so -12 >> 1 stays negative and gives -6. The unsigned right shift >>> always fills with 0, so -12 >>> 1 gives the large positive 2147483642. Java has no unsigned int type, so >>> is how you treat the 32 bits as plain switches without a sign.

Shifting the other way can reach the sign bit too. 1 << 31 puts a single 1 in position 31, which is the most negative int, -2147483648, also known as Integer.MIN_VALUE.

Reading and changing one bit

How do you look at just one switch, say position 2 of a? Slide it down to position 0 and keep only that bit: (a >> 2) & 1. The & 1 clears every other position, so the answer is 1 when the bit is on and 0 when it is off. For 12 it is 1 at position 2 and 0 at position 0.

To change one bit, build a number that has a 1 only at that position, called a mask. 1 << k is the mask for position k. Then pick the operator by what you want to happen:

  • Turn bit 0 on with OR: a | (1 << 0) gives 0000 1101, which is 13.
  • Turn bit 2 off with AND and the flipped mask: a & ~(1 << 2) keeps everything except position 2, giving 8.
  • Flip bit 3 with XOR: a ^ (1 << 3) turns the 8 off, giving 4.

Reading a bit and these three changes work the same way for any position from 0 to 31, and with 1L << k for a long up to 63.

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:

Top: a = 12 is 0000 1100, a - 1 = 11 is 0000 1011, a AND (a - 1) = 0000 1000 = 8. Bottom: -a is 1111 0100 in its lowest 8 bits, a AND -a = 0000 0100 = 4. Position 2 is highlighted.

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) keeps the left part and wipes out the orange bit, which leaves 8. In short, x & (x - 1) clears the lowest 1 bit of x.

Now the bottom three rows. In two's complement, -a is "flip every bit, then add 1". The flip turns position 2 off and positions 1 and 0 on, and the added 1 carries back up to position 2. So -a agrees with a at position 2 and below, and is the opposite of a everywhere above it. AND-ing the two keeps only the orange bit: a & -a is 4.

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)) == 0 says false for 12, which has two bits on, and true for 8. The x > 0 part is needed because 0 and one negative number would pass the check without it.

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 for k from 0 to 31 and adds up the answers. That always takes 32 steps, even for 12, which has only two bits on.

Clearing the lowest 1 bit gives a shorter loop: repeat x &= x - 1 until x is 0 and count the rounds. Each round removes exactly one 1, so the number of rounds is the answer. For 12 that is two rounds: 12 becomes 8, then 0.

Java has this built in as Integer.bitCount(x), with Long.bitCount for a long. On 12, 0 and the negative inputs -12, -1 and Integer.MIN_VALUE, all three give the same counts.

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], where every value has a partner except one. Start a result at 0 and XOR each value into it:

XOR of 12, 10, 12 step by step: result starts at 0000 0000, becomes 0000 1100 = 12, then 0000 0110 = 6, then 0000 1010 = 10. The second 12 flips positions 3 and 2 again, undoing the first 12.

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 becomes a set of up to 32 items, numbered 0 to 31. Then 12, with positions 3 and 2 on, is the set {2, 3}, and 10 is {1, 3}. The operators from the first picture turn into set operations:

  • Union: a | b is {1, 2, 3}, which is 14.
  • Shared items: a & b is {3}, which is 8. When this is 0, the sets have nothing in common.
  • Difference: a & ~b is what is in a but not in b, {2}.
  • Size: Integer.bitCount(a) is 2.

Sets stored this way are called bitmasks. To list every subset of n items, count mask from 0 up to (1 << n) - 1. For three items that is 0 to 7, eight different patterns of the three low bits, so eight different subsets.

The toolkit as one Java program

Everything so far fits in one class. The helper show prints a label, the lowest eight bits and the value, so each line reads like a row of the pictures. Three methods count 1 bits: countEveryPosition checks all 32 positions, countOnes clears the lowest 1 bit until nothing is left, and countByRemainder uses % 2 and / 2 as on paper. The method isPowerOfTwo is the check from the lowest-bit section, unpaired XORs an array, and members lists the positions that are on.

The main method runs every idea above on 12 and 10, then on 0, -12, -1 (all 32 bits on) and Integer.MIN_VALUE (only position 31 on), and ends with two traps: countByRemainder on -12, and isPowerOfTwoNoSignCheck, the power check without x > 0.

Java
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:

Output
-- 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 & b is 0000 1000 = 8, and ~a is 1111 0011 = -13, negative because position 31 is now on. Under "-- lowest 1 bit of a --", the lines a & (a - 1) and a & -a give 8 and 4, as in the second picture. The power-of-two line says true only for 8.

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], 5 in a longer list, and -12 in [-12, 4, 4], so negative values cancel the same way. The last line of the sets block lists all eight subsets of {0, 1, 2}, in the order the counter mask produces them.

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 shows it. In Java the remainder of a negative number divided by 2 is 0 or -1, never 1, so the remainders of -12 add up to a negative count. Use & and the shifts when a negative input is possible.

A loop with >> may never end. The output line -1 >> 1 = -1 shows why: copying the sign bit keeps a negative number negative, so while (x != 0) x >>= 1; spins forever on -12. A test run capped at 1,000 shifts ended with x still at -1. The same loop with >>> brings zeros in from the left and reached 0 after 32 shifts.

Shift distances wrap around. The line ending in 1 << 32 = 1 is not a typo. Java uses only the lowest five bits of the distance for an int, so 32 acts like 0. Use 1L << k when k can reach 32, which gives 4294967296 in that same line.

Zero and the sign bit fool the power-of-two check. Without x > 0, the last output line says true for both 0 and Integer.MIN_VALUE. 0 has no bits on to clear, and Integer.MIN_VALUE has a single 1 bit, but it is the sign bit, so the number is negative.

Operator precedence. Java evaluates == before &, ^ and |. This small class checks whether 12 is even, but without parentheses:

Java
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:

Output
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 == 0 first, which is a boolean, and an int cannot be AND-ed with a boolean. Writing (x & 1) == 0 fixes it.

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 countEveryPosition on any int, because it visits every position, while countOnes takes one round per bit that is on, two rounds for 12.
  • Time: O(n) and space O(1) for unpaired 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.
  • Time: O(n ยท 2n) to list every subset of n items with members, because there are 2n masks and listing one means checking its n positions (the members helper simply checks all 32).

Where to go next

Problems where XOR cancels pairs:

  • Single Number is the [12, 10, 12] idea on a full array.
  • Missing Number pairs each value with its index, so the one missing value is left over.

Problems that count 1 bits:

Problems built on the lowest 1 bit:

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: