ccomparebit-manipulationbitbitwise-xor

how does the bitwise operator compare the binary in c?


How does the bitwise operator compare the binary?

long num1 = 22; //00010110
long num2 = 21; //00010101

if ((num1 ^ num2) == 0) {
    printf("its equal\n");
    printf("%li\n", num1);
    printf("%li\n", num2);
}
else {
    printf("not equal\n");
}
    
//$> not equal

Does ^ XOR operator do a for loop for each bit?


Solution

  • It really depends on the implementation but most processors have a XOR (aka EOR) instruction. Even 8-bit CPUs have one.

    So no it doesn't loop on each bit at compiler level. Machine code instructions can process all bits in one call (also true for bitwise or, and and not operators).

    The compiler could have to create a loop if the data type is wider than the register type though (if 32 bit register machine is processing 64 bit integers for instance 2 calls to XOR instruction will be issued, probably not worth a loop though)