按位反转整数问题
Write a C function to swap the bits of a unsigned int so that its bits become the mirror image of the char. MSBs become its LSBs, e.g. 0111100011110111 binary should become 1110111100011110 binary.
方法一:(最最容易想到的办法)
unsigned
int ReverseBitsInWord00(unsigned int Num)
{
unsigned int ret = 0;
int i;
for(i=0;i<32;i++)
{
ret <<= 1;
ret |= Num & 1;
Num >>= 1;
}
return ret;
}
上面的程序通过每次取传入参数的最后一位( Num & 1),然后与要返回的结果相 “ 或 ”,把传入参数 Num 右移 1 位,要返回的结果左移一位,来实现数字反转的。