问题:
写一个函数 unsigned RevBit(unsigned val);
unsigned x = RevBit(0xf0ec9999);
x应该为 0x9999370f。
0xf0ec9999 == 11110000111011001001100110011001(二进制)
0x9999370f == 10011001100110010011011100001111(二进制)思路:相邻两位互调位置(即一位换一位),再相邻的两位换两位,在相邻的四位与四位互调位置,再八位与八位互调位置,最后前十六位和后十六位互换位置,完成32位整数逆转。思路与归并排序相似。
代码:
#include <stdio.h>;
unsigned RevBit(unsigned x)
{
x=(x&0x55555555)<<1|(x>>1)&0x55555555;
x=(x&0x33333333)<<2|(x>>2)&0x33333333;
x=(x&0x0f0f0f0f)<<4|(x>>4)&0x0f0f0f0f;
x=(x&0x00ff00ff)<<8|(x>>8)&0x00ff00ff;
x=x<<16|x>>16;
return x;
}
int main()
{
unsigned x = RevBit(0xf0ec9999);
printf("%x\n",x);
return 0;
}
更多解法:
http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious