Even parity of a unsigned int [duplicate]

天涯浪子 提交于 2019-12-04 16:13:33

Option #1 - iterate the bits in the "obvious" way, at O(number of bits):

int has_even_parity(unsigned int x)
{
    int p = 1;
    while (x)
    {
        p ^= x&1;
        x >>= 1; // at each iteration, we shift the input one bit to the right
    }
    return p;

Option #2 - iterate only the bits that are set to 1, at O(number of 1s):

int has_even_parity(unsigned int x)
{
    int p = 1;
    while (x)
    {
        p ^= 1;
        x &= x-1; // at each iteration, we set the least significant 1 to 0
    }
    return p;
}

Option #3 - use the SWAR algorithm for counting 1s, at O(log(number of bits)):

http://aggregate.org/MAGIC/#Population%20Count%20%28Ones%20Count%29

You can't access an integer as an array,

unsigned x = ...;
// x[0]; doesn't work

But you can use bitwise operations.

unsigned x = ...;
int n = ...;
int bit = (x >> n) & 1u; // Extract bit n, where bit 0 is the LSB

There is a clever way to do this, assuming 32-bit integers:

unsigned parity(unsigned x)
{
    x ^= x >> 16;
    x ^= x >> 8;
    x ^= x >> 4;
    x ^= x >> 2;
    x ^= x >> 1;
    return x & 1;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!