Reverse bits
Reverse the order of the bits in a number, one bit at a time, for a fixed 8-bit width.
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
- (n >> i) & 1 isolates bit i of n; result <<= 1 then result |= bit appends it as the new lowest bit of result.
- .NET actually uses 32 or 64 bits; this lesson fixes the width at 8 so the animation stays readable.
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.