Reverse Bits

Reverse the order of the 32 bits of an int, so the bit at position 0 ends at position 31.

Given a 32-bit unsigned integer n, one whose bits are read as a plain count with no sign, return the number whose bits are the bits of n in reverse order: bit 0 becomes bit 31, bit 1 becomes bit 30, and so on. Java has no unsigned int, so the input and output are ordinary int values, and only their bit patterns matter.

Example 1
Input: 00000010100101000001111010011100 (43261596)
Output: 00111001011110000010100101000000 (964176192)
Example 2
Input: 11111111111111111111111111111101 (4294967293 unsigned, -3 as a Java int)
Output: 10111111111111111111111111111111 (3221225471 unsigned, -1073741825 as a Java int)
Solution

The Idea

Reversing the digits of a number is something you could do on paper: 1230 read backwards is 0321. This problem asks for the same thing in binary, where every digit is a 0 or a 1, called a bit. A Java int has exactly 32 bits, and each has a position, numbered from 0 on the right up to 31 on the left.

Look at the picture below. The row labelled "input n" is Example 1, 43261596, with all 32 bits written out and their positions above them. The row labelled "reversed" is the answer, 964176192. Bit 2 of the input is a 1, and it lands at position 29. Bit 0 is a 0, and it lands at position 31.

The 32 bits of 43261596 with positions 31 to 0, and the reversed bits below them. Bit 2 moves to position 29 and bit 0 moves to position 31: a bit at position p ends at position 31 - p.

So, as the line under the picture says, a bit at position p ends at position 31 - p. The zeros on the left count too: the input starts with six zeros at positions 31 to 26, and in the answer those zeros fill positions 5 to 0.

How can a program move every bit to its mirror place? Working out 31 - p for each bit and setting the bit there would do it. But there is a simpler way, the same one you would use for the digits on paper.

To reverse 1230 by hand, take its last digit, 0, and write it down. Then take the next digit from the right, 3, and write it after the 0, then 2, then 1. Every digit written later pushes the earlier ones one place further left, so the last digit of 1230 ends up first.

Bits work the same way. Read the input from the right, one bit at a time, and append each bit to the right end of the answer. The bit read first, from position 0, is pushed left once by each of the 31 bits appended after it, so it lands at position 31.

Solution Approach

Three questions stand between the paper method and code: how to read the lowest bit of the input, how to append it to the answer, and how many times to repeat. Doing the work in fewer steps, for a method that is called very often, is an optional extra.

Reading the lowest bit

How do we read the bit at position 0? The & operator, bitwise AND, puts n next to another number and gives a 1 at each position where both of them have a 1. The number 1 has a single 1, at position 0, so n & 1 keeps only bit 0 of n. Example 1 ends in ...11100, so n & 1 is 0 there.

To reach the next bit, shift n one place to the right with n >>>= 1. Every bit moves down one position, bit 0 falls off, and bit 1 becomes the new bit 0. After one shift Example 1 ends in ...1110, and after two in ...111, so the third read gives 1.

Why >>> and not >>? A Java int stores its 32 bits in two's complement: position 31 counts as -231 instead of +231, so any int with a 1 there is negative. That is why the input of Example 2, 4294967293 as an unsigned number, is -3 as a Java int. The shift >> copies that top bit into the gap on the left, to keep a negative number negative. The shift >>> always brings in a 0, so n holds just the bits not yet read.

Appending a bit to the result

How does a bit go onto the right end of the answer? Say the answer is built up in a variable named result, starting at 0. The shift result << 1 moves every bit of result one place left, which leaves a 0 at position 0. The | operator, bitwise OR, keeps a 1 wherever either number has one, so it writes the new bit into that free place. Together, (result << 1) | (n & 1) appends the lowest bit of n to result, like writing 3 after the 0 on paper.

On a 4-bit number, 1011, the reading and appending go as in the table below.

StepLowest bit of nresult after appending itn after the shift
111101
211110
301101
4111010

The final result, 1101, is 1011 read backwards. The 1 appended in step 1 was pushed left by each of the three later steps, so it now sits at the top.

How many times to repeat

When can the loop stop? It looks tempting to stop once n is 0, because every bit left in it is then a 0. But those zeros still have to be appended. Take the input 1: after one step n is 0 and result is 1, yet the answer is a 1 at position 31. That 1 gets there only if result is shifted left 31 more times, once for each zero still to come. So the loop runs exactly 32 times, once per bit of an int, whatever the input.

Fewer steps for many calls (optional)

What if the method is called millions of times? The 32-step loop is already a fixed amount of work, but there are ways to do fewer steps. A group of 8 bits is called a byte, and an int holds four of them. A table of 256 entries can hold the reversal of every possible byte. Reversing an int is then four lookups, with the four results put back in the opposite order.

Java's own Integer.reverse(n) takes another route. In JDK 25 it swaps neighbouring bits, then neighbouring pairs of bits, then neighbouring groups of four, each with two shifts and one mask, a constant whose 1s pick out the bits to keep. It then reverses the order of the four bytes with Integer.reverseBytes. In real code, calling Integer.reverse(n) is the simplest choice.

Java Solution

The method reverseBits works in these steps:

  1. First, set result to 0. It collects the bits of n in reverse order.
  2. Run a for loop with a counter i exactly 32 times, once per bit of an int.
  3. Inside the loop, append the lowest bit of n to result with result = (result << 1) | (n & 1).
  4. Then shift n right with n >>>= 1, so the next bit moves into position 0 and a 0 comes in on the left.
  5. After 32 passes, every bit of n has been appended, and the method returns result.

Two small helpers handle the printing. The method bits writes all 32 bits of a number, because Integer.toBinaryString leaves out the zeros on the left. The method show prints an input, an arrow, its reversal, and the reversal's int value in brackets.

The main method runs both examples, then 1, 0, -1 and Integer.MIN_VALUE (a single 1, at position 31), and finally checks seven inputs against Integer.reverse.

Java
public class ReverseBits {

    public static int reverseBits(int n) {
        int result = 0;
        for (int i = 0; i < 32; i++) {
            result = (result << 1) | (n & 1);   // append n's lowest bit to result
            n >>>= 1;                           // unsigned shift: a 0 comes in on the left
        }
        return result;
    }

    // all 32 bits of x, leading zeros included
    static String bits(int x) {
        return String.format("%32s", Integer.toBinaryString(x)).replace(' ', '0');
    }

    static void show(int n) {
        int r = reverseBits(n);
        System.out.println(bits(n) + " -> " + bits(r) + " (" + r + ")");
    }

    public static void main(String[] args) {
        show(0b00000010100101000001111010011100);   // Example 1: 43261596
        show(-3);                                   // Example 2: 11...101
        show(1);
        show(0);
        show(-1);
        show(Integer.MIN_VALUE);
        boolean same = true;
        for (int n : new int[] {43261596, -3, 1, 0, -1, Integer.MIN_VALUE, 123456789}) {
            same &= reverseBits(n) == Integer.reverse(n);
        }
        System.out.println("same as Integer.reverse: " + same);
    }
}

Running it prints:

Output
00000010100101000001111010011100 -> 00111001011110000010100101000000 (964176192)
11111111111111111111111111111101 -> 10111111111111111111111111111111 (-1073741825)
00000000000000000000000000000001 -> 10000000000000000000000000000000 (-2147483648)
00000000000000000000000000000000 -> 00000000000000000000000000000000 (0)
11111111111111111111111111111111 -> 11111111111111111111111111111111 (-1)
10000000000000000000000000000000 -> 00000000000000000000000000000001 (1)
same as Integer.reverse: true

Example 1 comes out as 00111001011110000010100101000000, which is 964176192. On the next line, -3 becomes 10111111111111111111111111111111. It prints as -1073741825 because its top bit is 1, and read as unsigned it is the 3221225471 of Example 2.

Look at the third line: the single 1 at position 0 ends at position 31, so the result is -2147483648. The line for Integer.MIN_VALUE is the same move the other way, and it prints 1. The inputs 0 and -1 come back unchanged, since all 32 of their bits are equal. The last line confirms that all seven results match Integer.reverse.

A version that loops while (n != 0) instead of 32 times gets the third line wrong: it returns 1 for the input 1. For Example 1 it returns 15065253 instead of 964176192, because it stops before the six zeros at the top are appended. Swapping >>> for >> in the 32-step loop gives the same results on these seven inputs. The copies of the top bit that >> brings in are never read, since the loop stops after 32 bits.

Complexity

The work is one loop of 32 steps, whatever number comes in.

  • Time: O(1), because the for loop always runs exactly 32 times, once per bit of an int, with two shifts, an AND and an OR in each pass.
  • Space: O(1), because the method keeps only result and the counter i, and shifts its own copy of n.