Computing the Parity

后端 未结 2 2008
眼角桃花
眼角桃花 2020-12-08 17:04

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

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 17:44

    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.

提交回复
热议问题