^ 运算符的用途是什么?

Bee*_*ype -4 c++ operators xor

运算符是^用来做什么的?它不适用于幂函数:

#include <iostream>

int main(){
    int x, y;

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

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ara 5

运算^符是按位XOR。以6和12为例

6 的二进制为:110

12 的二进制为:1100

异或遵循以下规则:“第一个或第二个,但不是两者”。这是什么意思?它的真值表应该很清楚:

A     B     A^B
0     0      0
0     1      1
1     0      1
1     1      0
Run Code Online (Sandbox Code Playgroud)

您可以看到唯一的1- 位是设置了或 A 或 B(但不是两者)的位。

回到第一个例子:

A    1100 => 12
B    0110 => 6
A^B  1010 => 10
Run Code Online (Sandbox Code Playgroud)