top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to findout the parity of a number?

+8 votes
443 views

A value has even parity if it has an even number of 1 bits. A value has an odd parity if it has an odd number of 1 bits. For example, 0110 has even parity, and 1110 has odd parity.

Can someone help me to write this code which returns 1 if number is having even parity else return zero.

int has_even_parity(unsigned int x) {
    return 
}
posted Feb 7, 2014 by Manu Lakaster

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Function returns 0 if n has odd parity, and returns 1 if n has even parity.

int has_even_parity(unsigned int n)
{
    bool parity = 1;
    while (n)
    {
        parity = !parity;
        n      = n & (n - 1);
    }        
    return parity;
}
answer Feb 7, 2014 by Satish Mishra
...