Saturday, June 5, 2010

bit reversal

#if _WIN64 || __amd64__ || _M_X64
#define IS_64_BIT
#else
#define IS_32_BIT
#endif

#ifdef IS_64_BIT
uint64_t bitRevInt32(uint64_t value)
{
  value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32;
  value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16;
  value = (value & 0x00ff00ff00ff00ff) << 8  | (value & 0xff00ff00ff00ff00) >> 8;
  value = (value & 0x0f0f0f0f0f0f0f0f) << 4  | (value & 0xf0f0f0f0f0f0f0f0) >> 4;
  value = (value & 0x3333333333333333) << 2  | (value & 0xcccccccccccccccc) >> 2;
  value = (value & 0x5555555555555555) << 1  | (value & 0xaaaaaaaaaaaaaaaa) >> 1;
  return value;
}
#endif

uint32_t bitRevInt32(uint32_t value)
{
  value = (value & 0x0000ffff) << 16 | (value & 0xffff0000) >> 16;
  value = (value & 0x00ff00ff) << 8  | (value & 0xff00ff00) >> 8;
  value = (value & 0x0f0f0f0f) << 4  | (value & 0xf0f0f0f0) >> 4;
  value = (value & 0x33333333) << 2  | (value & 0xcccccccc) >> 2;
  value = (value & 0x55555555) << 1  | (value & 0xaaaaaaaa) >> 1;
  return value;
}

unsigned char bitRevChar(unsigned char value)
{
  value = (value & 0x0f) << 4 | (value & 0xf0) >> 4;
  value = (value & 0x33) << 2 | (value & 0xcc) >> 2;
  value = (value & 0x55) << 1 | (value & 0xaa) >> 1;
  return value;
}

No comments:

Post a Comment