按位反转整数问题
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 位,要返回的结果左移一位,来实现数字反转的。
本文介绍了一种按位反转整数的方法,通过循环遍历每一位并将原数值的最低位移动到新数值的最高位来实现。这种方法适用于任何无符号整数,并提供了详细的C语言实现代码。
124

被折叠的 条评论
为什么被折叠?



