Frage

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?

War es hilfreich?

Lösung

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;
}

Andere Tipps

The problem is that literals 1100 and 0110 are not binary literals. The first one is decimal literal 1100 and the second one is octal literal 0110 that in decimal is equivalent to 24. You should use string literals to achive the desired result. For example consider results of the following code snipet

    std::bitset<4> a = 1100, b = 0110, c;
    c = a ^ b;
    std::cout << "a = " << a << std::endl;
    std::cout << "b = " << b << std::endl;
    std::cout << "c = " << c << std::endl;

    std::bitset<4> a1( "1100" ), b1( "0110" ), c1;
    c1 = a1 ^ b1;
    std::cout << "a1 = " << a1 << std::endl;
    std::cout << "b1 = " << b1 << std::endl;
    std::cout << "c1 = " << c1 << std::endl;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top