0

From the Bit Twiddling Hacks, I see this trick:

unsigned char b;  // byte value to compute the parity of

bool parity = 
  (((b * 0x0101010101010101ULL) & 0x8040201008040201ULL) % 0x1FF) & 1;

I have spent several hours try to understand why it needs to modulus 0x1FF. How does it work? Why it has to be 0x1FF?

(b * 0x0101010101010101ULL) makes 8 copies of b and set them in each byte.

((b * 0x0101010101010101ULL) & 0x8040201008040201ULL) extract different bits from each copy.

But I couldn't figure out the gap in the third step modulus 0x1FF.

The last step is checking whether the last bit is 1 or not.

Any people can help to explain it a little bit? A good example will be very helpful.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
user791961
  • 57
  • 7

1 Answers1

0

The multiply-and operation multiplies each bit in b by increasing powers of 512. 512 is (511+1). Squaring that gives (511+1)*(511+1)=511*511+2*511+1 or 513*511+1, which will give 1 when modding with 511. This continues for each of the remaining bits.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • `b = abcdefgh, b * 0x0101010101010101 = 0xabcdefgh abcdefgh abcdefgh abcdefgh abcdefgh abcdefgh abcdefgh abcdefgh` – user791961 Oct 18 '15 at 04:13
  • '((b * 0x0101010101010101ULL) & 0x8040201008040201ULL) = 0x a 00000000b 00000000c 00000000d 00000000e 00000000f 00000000g 00000000h'
    '= 0x a * 512^7 + b * 512^6 + c * 512^5 + d * 512^4 + e * 512^3 + f * 521^2 + g * 512^1 + h'
    , for 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),
    we know the above equation `= a + b + c + d + e + f + g + h (mod 512 - 1)`, this adds all bits of b, and how it works.
    – user791961 Oct 18 '15 at 04:34