c++operatorsxor

What is the purpose of the ^ operator?


What is the ^ operator used for? It's not for the power function:

#include <iostream>

int main(){
    int x, y;

    cout << (x^y) << endl; /* this is the unkown (X^Y)*/

    return 0;
}

Solution

  • The ^ operator is the bitwise XOR. Take for example 6 and 12

    6 in binary is: 110

    12 in binary is: 1100

    The xor follows this rule: "The first or the second but not both". What does it mean? Its truth table should make it clear:

    A     B     A^B
    0     0      0
    0     1      1
    1     0      1
    1     1      0
    

    You can see that the only 1-bits are those where or A or B (but not both) are set.

    Back to the first example:

    A    1100 => 12
    B    0110 => 6
    A^B  1010 => 10