rzv
rzv

Reputation: 11

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)

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

Upvotes: 1

Views: 2781

Answers (2)

JonS
JonS

Reputation: 651

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

Upvotes: 0

ouah
ouah

Reputation: 145839

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

Upvotes: 2

Related Questions