Reverse bit pattern in C

后端 未结 6 1628
猫巷女王i
猫巷女王i 2021-01-05 05:16

I am converting a number to binary and have to use putchar to output each number.

The problem is that I am getting the order in reverse.

Is the

6条回答
  •  情书的邮戳
    2021-01-05 05:57

    Here are functions I've used to reverse bits in a byte and reverse bytes in a quad.

    inline unsigned char reverse(unsigned char b) {
        return (b&1 << 7)
             | (b&2 << 5)
             | (b&4 << 3)
             | (b&8 << 1)
             | (b&0x10 >> 1)
             | (b&0x20 >> 3)
             | (b&0x40 >> 5)
             | (b&0x80 >> 7);
    }
    
    inline unsigned long wreverse(unsigned long w) {
        return ( ( w     &0xFF) << 24)
             | ( ((w>>8) &0xFF) << 16)
             | ( ((w>>16)&0xFF) << 8)
             | ( ((w>>24)&0xFF) );
    }
    

提交回复
热议问题