CSAPP-3.23 二进制数逆转

例:0x0001 -> 0x1000

思路一

result = 0x00000000;
resuilt(从左到右)第i位与x(从右到左)第i位进行“或”运算
与0“或”运算的结果为其本身,而result全是0

unsigned int fun_a(unsigned int x)
{
    unsigned int result = 0;
    for(int i = 0; i < 32; i++) {
       result = (result << 1) | (x & 1);
       x = x >> 1;
    }
    return result;
}

思路二

先奇偶位交换,然后以2位为一组,组间再奇偶交换,然后4位一组,8位,16位…

unsigned int fun_b(unsigned int x)
{
    x = ((x >> 1) & 0x55555555) | ((x << 1) & 0xaaaaaaaa);
    x = ((x >> 2) & 0x33333333) | ((x << 2) & 0xcccccccc);
    x = ((x >> 4) & 0x0f0f0f0f) | ((x << 4) & 0xf0f0f0f0);
    x = ((x >> 8) & 0x00ff00ff) | ((x << 8) & 0xff00ff00);
    x = ((x >> 16)& 0x0000ffff) | ((x << 16)& 0xffff0000);

    return x;
}
 

当然,也可以先把高16位和低16位交换,分别再对16位进行8位交换,递归至2位交换