Reverse bits

Reverse the order of the bits in a number, one bit at a time, for a fixed 8-bit width.

Time O(1)Space O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Reading n from its lowest bit upward and placing each bit into result from the lowest position upward, after shifting result left first, builds result up in the opposite bit order from n. After 8 iterations every bit has moved to its mirrored position.

Code

public static int ReverseBits(int n) {
    int result = 0;
    for (int i = 0; i < 8; i++) {
        result <<= 1; // make room for the next bit
        result |= (n >> i) & 1; // copy bit i of n into the lowest bit
    }
    return result;
}

Tips

In the .NET library

A common mistake is to shift result before the loop has anything in it, or to forget the final shift, which drops the last bit. Tracing all 8 iterations is the easiest way to check the result.