2
/*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.
 *Return 1 iff x has even parity.
 */

int has_even_parity(unsigned int x) {

}

I'm not sure where to begin writing this function, I'm thinking that I loop through the value as an array and apply xor operations on them. Would something like the following work? If not, what is the way to approach this?

int has_even_parity(unsigned int x) {
    int i, result = x[0];
    for (i = 0; i < 3; i++){
        result = result ^ x[i + 1];
    }
    if (result == 0){
        return 1;
    }
    else{
        return 0;
    }
}
user2917692
  • 147
  • 1
  • 3
  • 10
  • See here: http://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer – Linuxios Feb 05 '14 at 22:16
  • See here: [stackoverflow.com/questions/21617970/how-to-check-if-value-has-even-parity-of-bits-or-odd](http://stackoverflow.com/questions/21617970/how-to-check-if-value-has-even-parity-of-bits-or-odd). – Troyseph Oct 27 '15 at 10:00

2 Answers2

3

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

barak manos
  • 29,648
  • 10
  • 62
  • 114
1

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;
}
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415