What's up with this reversing bit order function?
Posted
by MattyW
on Stack Overflow
See other posts from Stack Overflow
or by MattyW
Published on 2010-04-24T19:50:26Z
Indexed on
2010/04/24
19:53 UTC
Read the original article
Hit count: 142
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;
}
© Stack Overflow or respective owner