异或(^)运算符又称XOR运算符
定义:当参与运算的两位相同时为0,不同时为1。0^0=0,0^1=1, 1^0=1, 1^1=0。
特点:1. a^a=0
2. a^b=b^a
3. a^b^b=a
应用:1. 按位异或实现某特定位的翻转
2. 按位异或实现两个数值的交换,不用中间临时变量。例如:
a=10100001, b=00000110
a=a^b; //a=10100111
b=b^a; //b=10100001
a=a^b; //a=00000110
int swapa = 100; int swapb = 200; cout << swapa << " " << swapb <<endl; swapa = swapa^swapb; swapb = swapa^swapb; swapa = swapa^swapb; cout << swapa << " " << swapb <<endl;
3. 使用异或,求平均数
int foo(int x, int y) { return (x&y) + ((x^y)>>1); }