Search code examples
c++xor

What's the error with this xor


Why, when using this xor in C++,

int main() {
    bitset<4> a=1100, b=0110,c;
    c = a ^ b;
    cout << c;
    return 0;
}

is the result 0100?


Solution

  • Those constants aren't in binary, that's why. 1100 decimal is 10001001100 binary. 0110 octal is 1001000 binary. (Why octal for the second one? Because a constant that starts with a leading zero and consists only of digits 0..7 is octal in C++.)

    When you truncate both to 4 bits, you get 1100 binary XORed with 1000 binary, which gives 0100 binary.

    Try this instead (assuming your compiler supports the nonstandard prefix 0b for binary literals):

    int main() {
        bitset<4> a=0b1100, b=0b0110,c;
        c = a ^ b;
        cout << c;
        return 0;
    }
    

    Alternately, specify your constants in hexadecimal:

    int main() {
        bitset<4> a=0xC, b=0x6,c;
        c = a ^ b;
        cout << c;
        return 0;
    }
    

    or as string constants: (C++11)

    int main() {
        bitset<4> a( "1100" ), b( "0110" ),c;
        c = a ^ b;
        cout << c;
        return 0;
    }