I was looking into bitwise operators and bit manipulation and stumbled upon this thread: bitParity - Finding odd number of bits in an integer
To summarize, the user asked for a function, int bitParity(int x)
, that returns 1 if there are an odd number of 0's in the two's complement representation of the integer passed in, otherwise, the function returns 0. All of this had to be done using only bitwise operators.
I am having no luck with trying to understand the accepted response and was hoping for some insight into it.
The solution:
x ^= x >> 16
x ^= x >> 8
x ^= x >> 4
x ^= x >> 2
x ^= x >> 1
x &= 1;
From what I think I can gather, the result of XOR between two same length, continuous sub bit vectors always has the same parity of 0's as the original bit vector. So by repeatedly applying the XOR operator on a bit vector and its shifted counter part until you reach a sub bit vector of length 1, you can chain the result to the entire original bit vector. Any correction to my thinking and further explanation would be appreciated.
I am confused as to how the right shift works to create "sub vectors" considering that it would be an arithmetic right shift since x
is a signed value. I also do not understand why XOR between two sub bit vectors nets will have an odd number of 0's if and only if the original did.