reverse bits in byte ansi C

狂风中的少年 提交于 2019-12-24 07:08:22

问题


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)

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

回答1:


Check the "Bit Twiddling Hacks" page for the explanation:

Reverse the bits in a byte with 7 operations (no 64-bit) http://graphics.stanford.edu/~seander/bithacks.html




回答2:


Direct link to the correct Bit Twiddling Hacks section.

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


来源:https://stackoverflow.com/questions/22338208/reverse-bits-in-byte-ansi-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!