What's up with this reversing bit order function?
- by MattyW
I'm rather ashamed to admit that I don't know as much about bits and bit manipulation as I probably should. I tried to fix that this weekend by writing some 'reverse the order of bits' and 'count the ON bits' functions. I took an example from here but when I implemented it as below, I found I had to be looping while < 29. If I loop while < 32 (as in the example) Then when I try to print the integer (using a printBits function i've written) I seem to be missing the first 3 bits. This makes no sense to me, can someone help me out?
int reverse(int n)
{
int r = 0;
int i = 0;
for(i = 0; i < 29; i++)
{
r = (r << 1) + (n & 1);
n >>=1;
}
return r;
}