简体   繁体   English

字节ansi C中的反向位

[英]reverse bits in byte ansi C

I have a function that reverse the bits in a byte but i don't understand the syntax. 我有一个功能,可以反转一个字节中的位,但我不理解语法。 Why is used 0x0802U & 0x22110U and other binary operations(what are this numbers) 为什么使用0x0802U和0x22110U以及其他二进制运算(此数字是什么)

unsigned char reverse(unsigned char B)
{
return (unsigned char)(((b * 0x0802U & 0x22110U) | (b * 0x8020U & 0x88440U)) * 0x10101U >> 16);
}

Check the "Bit Twiddling Hacks" page for the explanation: 查看“ Bit Twiddling Hacks”页面以获取解释:

Reverse the bits in a byte with 7 operations (no 64-bit) http://graphics.stanford.edu/~seander/bithacks.html 通过7个操作(无64位)反转字节中的位 http://graphics.stanford.edu/~seander/bithacks.html

Direct link to the correct Bit Twiddling Hacks section . 直接链接到正确的Bit Twiddling Hacks部分

You should just do the math to see why those numbers were chosen. 您应该算一下数学,看看为什么选择了这些数字。

                                         abcd efgh
    *                          0000 1000 0000 0010
    ----------------------------------------------
                          0abc defg h00a bcde fgh0
    &                     0010 0010 0001 0001 0000
    ----------------------------------------------
                          00b0 00f0 000a 000e 0000


                                         abcd efgh
    *                          1000 0000 0010 0000
    ----------------------------------------------
                     0abc defg h00a bcde fgh0 0000
    &                0000 1000 1000 0100 0100 0000
    ----------------------------------------------
                     0000 d000 h000 0c00 0g00 0000


                          00b0 00f0 000a 000e 0000
    |                0000 d000 h000 0c00 0g00 0000
    ----------------------------------------------
                          d0b0 h0f0 0c0a 0g0e 0000
    *                     0001 0000 0001 0000 0001
    ----------------------------------------------
      d0b0 h0f0 dcba hgfe dcba hgfe 0c0a 0g0e 0000
    >> and convert to 8-bits
    ----------------------------------------------
                                         hgfe dcba

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM