I don\'t fully understand this algorithm of calculating the parity bit. Can someone please explain in detail?
The following code is taken from the \'Hacker\'s Deligh
If x had only 1 bit, clearly ((x ^ (x >> 1)) & 1 would calculate the parity (just xor the bits with each other).
This pattern can be extended to more bits.
If you have 4 bits, you get (at least, this is one way to do it)
y = x ^ (x >> 1);
y = y ^ (y >> 2);
return y & 1;
where the bits do this:
x = a b c d
y = a a^b b^c c^d
y = a a^b a^b^c a^b^c^d
If you extend the pattern all the way to 32 bits you get the code you showed in the question.