首先取得N比特位的长度,然后把N每个末尾BIT的值保持在VAL中:
uint32_t reverseBits(uint32_t n) {
int length = sizeof(uint32_t)*8;
int val = 0;
while(length--){
if(n&1)
val = val << 1|0x1;
else
val = val << 1;
n = n >>1;
}
return val;
}
需要理解学习更快的算法:
uint32_t reverseBits(uint32_t n) {
unsigned int y=0;
unsigned int bit[32],i;
for(i=0;i<=31;i++)
{
bit[i]=n<<i;
bit[i]=bit[i]>>31;
bit[i]=bit[i]<<i;
}
for(i=0;i<=31;i++)
{
y=y|bit[i];
}
return y;
}