Skip to content

Instantly share code, notes, and snippets.

@keichi
Created February 1, 2013 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keichi/4689406 to your computer and use it in GitHub Desktop.
Save keichi/4689406 to your computer and use it in GitHub Desktop.
#include <stdio.h>
unsigned int bitreverse(unsigned int x) {
x = (x & 0x55555555)<<1 | (x & 0xaaaaaaaa)>>1;
x = (x & 0x33333333)<<2 | (x & 0xcccccccc)>>2;
x = (x & 0x0f0f0f0f)<<4 | (x & 0xf0f0f0f0)>>4;
x = (x & 0x00ff00ff)<<8 | (x & 0xff00ff00)>>8;
x = (x & 0x0000ffff)<<16 | (x & 0xffff0000)>>16;
return x;
}
#define bitreverse_range(x,s) (bitreverse((x))>>(32-(s)))
int main()
{
int i;
for(i = 0; i < 128; ++i) {
printf("%d -> %d\n", i, bitreverse_range(i, 7));
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment