Possible Duplicate:
C reverse bits in unsigned integer
How does this code work to reverse bits in number?
Given a number n
with k
bits, (n < 2^k)
, is there a fast way to do it using bitwise? This is my slow
solution:
int reverse_bit(int n, int bit_size) {
bit_size--;
int result = 0;
while (n) {
if ((n & 1) == 1)
result += 1 * (1 << bit_size);
n >>= 1;
bit_size--;
}
return result;
}