While reading this: http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64BitsDiv
I came to the phrase:
The last step, which in
The modulo operation does not give you the inverted bits per se, it is just a binning operation.
b * 0x0202020202 = 01001010 01001010 01001010 01001010 01001010 0
The multiplication operation has a convolution property, which means it replicate the input variable several times (5 here since it's a 8-bit word).
That's the most tricky part of the hack. You have to remember that we are working on a 8-bit word : b = abcdefgh
, where [a-h] are either 1 or 0.
b * 0x0202020202 = abcdefghabcdefghabcdefghabcdefghabcdefgha
& 10884422010 = a0000f000b0000g000c0000h000d00000000e0000
Modulo has a peculiar property : 10 ≡ 1 (mod 9)
so 100 ≡ 10*10 ≡ 10*1 (mod 9) ≡ 1 (mod 9)
.
More generally, for a base b
, b ≡ 1 (mod b - 1)
so for all number a ≡ sum(a_k*b^k) ≡ sum (a_k) (mod b - 1)
.
In the example, base = 1024
(10 bits) so
b ≡ a0000f000b0000g000c0000h000d00000000e0000
≡ a*base^4 + 0000f000b0*base^3 + 000g000c00*base^2 + 00h000d000*base +00000e0000
≡ a + 0000f000b0 + 000g000c00 + 00h000d000 + 00000e0000 (mod b - 1)
≡ 000000000a
+ 0000f000b0
+ 000g000c00
+ 00h000d000
+ 00000e0000 (mod b - 1)
≡ 00hgfedcba (mod b - 1) since there is no carry (no overlap)