Saturday, March 31, 2007

parity

I got the question, of how do you compute the parity of an int? My first reaction was that, well, you make a loop, 32 times, shift right, and do an xor on the least significant bit. I mean, man, that is an easy question, why do you even ask?

I'm ashamed to say, that I should have thought more carefully. I woke up in the middle of the night, 8 hours later, and had a relevation:


public static final int parity(int i) {
i = (i>>16)^i;
i = (i>>8)^i;
i = (i>>4)^i;
i = (i>>2)^i;
i = (i>>1)^i;
return i&1;
}

No comments: