1

I was reading bit twiddling hacks for computing parity from this link: Bit Twiddling Hacks

For computing parity, there is a lookup method, which generates parity table for integers from 0 to 255 with 5 codes of line.

#define P2(n) n, n ^ 1, n ^ 1, n 
#define P4(n) P2(n), P2(n ^ 1), P2(n ^ 1), P2(n) 
#define P6(n) P4(n), P4(n ^ 1), P4(n ^ 1), P4(n) 
#define LOOK_UP P6(0), P6(1), P6(1), P6(0)

unsigned int table[256] = { LOOK_UP };

I checked the values P2(n) and P4(n) which calculates the parity for [0..15]. But I didn't understand the intuition behind these lines of code. How do these lines calculate the parity of [0..255]? I want to know the intuition and theory behind this recursive approach. Thanks in advance.

aroup
  • 315
  • 3
  • 13
  • As all of this code holds up when compiling with C, I suggest retagging as C. In modern C++, one could use `constexpr` to make this table – JVApen Dec 30 '18 at 07:58

1 Answers1

1

For P2, parity of bit set to 1 is trivial:

0b00 -> 0
0b01 -> 1
0b10 -> 1
0b11 -> 0

Prepend 00 doesn't change parity,
but prepend next 01 change parity:

0b0100 -> 1 // 0 ^ 1
0b0101 -> 0 // 1 ^ 1
0b0110 -> 0 // 1 ^ 1
0b0111 -> 1 // 0 ^ 1

Parity of 0b10.. is the same as 0b01.. and will change again with 0b11..

n ^ 1 allow the switch:

n | n ^ 1
--|--------
0 | 1
1 | 0

alternatively !n might have been chosen or other formula with same table

Hope you see the pattern now.

Jarod42
  • 203,559
  • 14
  • 181
  • 302