cxorparity

How to XOR all of the bits of a single number in C?


Is there a simple way to XOR all of the bits of a single number together, i.e. a unary XOR in C?

Something that has the effect of:

result = ^(0x45); // ( 0 ^ 1 ^ 0 ^ 0 ^ 0 ^ 1 ^ 0 ^ 1 = 1)
result = ^(0x33); // ( 0 ^ 0 ^ 1 ^ 1 ^ 0 ^ 0 ^ 1 ^ 1 = 0)

Solution

  • There's no special operator for that. You would need to do that manually as follows:

    unsigned int value = 0x45;
    unsigned int result = 0;
    while (value) {
        result ^= value & 1;
        value >>= 1;
    }
    

    You can also create a lookup table containing the parity for all 1 byte values:

    char parity[256] = { 0, 1, 1, 0, 1, 0, 0, 1,
                        ...
                         1, 0, 0, 1, 0, 1, 1, 0 };