2

I have to create a function bitParity(int x) that takes an integer and returns 1 if there is an odd number of 0's in the bit form of x, and 0 otherwise.

Ex: bitParity(5) = 0, bitParity(7) = 1 Legal ops: ! ~ & ^ | + << >>

My buddy shared his code with me, but when I did the calculation from scratch, it seems to get the opposite of what he gets, can someone please explain this code a little bit so I get the idea of how it functioning?

int bitParity(int x) {
x = ( x >> 16 ) ^ x;
x = ( x >> 8 ) ^ x;
x = ( x >> 4 ) ^ x;
x = ( x >> 2 ) ^ x;
x = ( x >> 1 ) ^ x;

    return (x & 1);
}
0xF1
  • 6,046
  • 2
  • 27
  • 50
  • The behavior of >> on signed values is unspecified. So you'd better make the argument *unsigned* if you want a predictable result. – Hans Passant Feb 03 '14 at 08:57

1 Answers1

0

This function is basically xoring all the bits of the input number and putting it at the LSB, hence gives 1 if there are odd number of 1s.

How it Works:

  • Take input of 8-bit, say 11001001.
  • For 8-bit input you need to start from 3rd statement of code: x = ( x >> 4 ) ^ x;
  • Doing so (Step 1), you get:

    x7  x6  x5  x4  x7^x3  x6^x2  x5^x1  x4^x0

where xi denotes ith bit of x.

  • Now Step 2: x = ( x >> 2 ) ^ x; gives:

    x6^x2^x4^x0           at the LSB of x, and
    x7^x3^x5^x1           at bit position 1 of x. Rest positions are not relevant.

  • Step 3: x = ( x >> 1 ) ^ x; which finally gives:

    x6^x2^x4^x0^x7^x3^x5^x1           at the LSB of x.

  • Last Step: return (x & 1); which returns value of this expression, which is xor of all the bits in x which is 1 if and only if number of 1s in x is odd.

  • You can extend this to 16-bit, 32-bit or 64-bit numbers.

  • Also, notice that finding odd number of 0s is equivalent to finding odd numbers of 1s, since total number of 1s and 0s add up to even number of bits.

  • Therefore, above code should work correctly for you

0xF1
  • 6,046
  • 2
  • 27
  • 50