C reverse bits in unsigned integer

前端 未结 12 892
一整个雨季
一整个雨季 2020-11-30 10:18

I\'m converting an unsigned integer to binary using bitwise operators, and currently do integer & 1 to check if bit is 1 or 0 and output, then right shift by 1 to divide

12条回答
  •  孤城傲影
    2020-11-30 11:03

    Reversing the bits in a word is annoying and it's easier just to output them in reverse order. E.g.,

    void write_u32(uint32_t x)
    {
        int i;
        for (i = 0; i < 32; ++i)
            putchar((x & ((uint32_t) 1 << (31 - i)) ? '1' : '0');
    }
    

    Here's the typical solution to reversing the bit order:

    uint32_t reverse(uint32_t x)
    {
        x = ((x >> 1) & 0x55555555u) | ((x & 0x55555555u) << 1);
        x = ((x >> 2) & 0x33333333u) | ((x & 0x33333333u) << 2);
        x = ((x >> 4) & 0x0f0f0f0fu) | ((x & 0x0f0f0f0fu) << 4);
        x = ((x >> 8) & 0x00ff00ffu) | ((x & 0x00ff00ffu) << 8);
        x = ((x >> 16) & 0xffffu) | ((x & 0xffffu) << 16);
        return x;
    }
    

提交回复
热议问题