14 October 2009

Reverse bits the easy way

typedef unsigned int uint;
uint reverse(uint val)
{
int i;
uint tval=0;

for(i=0; i<sizeof(val)*8; i++)
{
tval <<= 1;
tval |= val&1;
val >>= 1;
}

return tval;
}
typedef unsigned int uint;
uint reverse(uint val)
{
char i;
uint tval=0;

for(i=sizeof(val)*8; val; i--)
{
tval <<= 1;
tval |= val&1;
val >>= 1;
}

return (tval<<i);
}

Reference:
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive

No comments:

Post a Comment