Search code examples
cbit

How can I check if a value has even parity of bits or odd?


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.

I have to return 1 if x has even parity.

int has_even_parity(unsigned int x) {
    return
}

Solution

  • Try:

    int has_even_parity(unsigned int x){
        unsigned int count = 0, i, b = 1;
    
        for(i = 0; i < 32; i++){
            if( x & (b << i) ){count++;}
        }
    
        if( (count % 2) ){return 0;}
    
        return 1;
    }