異或,英文為exclusive OR,縮寫成xor
異或(xor)是一個數學運算符。它套用於邏輯運算。異或的數學符號為“⊕”,計算機符號為“xor”。其運算法則為:
a⊕b = (¬a ∧ b) ∨ (a ∧¬b)
如果a、b兩個值不相同,則異或結果為1。如果a、b兩個值相同,異或結果為0。
異或也叫半加運算,其運算法則相當於不帶進位的二進制加法:二進制下用1表示真,0表示假,則異或的運算法則為:0⊕0=0,1⊕0=1,0⊕1=1,1⊕1=0(同為0,異為1),這些法則與加法是相同的,只是不帶進位,所以異或常被認作不進位加法。
異或略稱為XOR、EX-OR
程式中有兩種演運算元:XOR、⊕。
使用方法如下
z = x ⊕ y
z = x xor y
基本介紹
- 中文名:異或
- 外文名:exclusive OR
- 數學符號:⊕
- 英文簡稱:xor
- 程式符號:^
運算法則





a | b | a⊕b |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
邏輯



作用
- | 00000000 |
xor | 00000000 |
------------- | |
結果 | 00000000 |
- | 11111111 |
xor | 00000000 |
-------------- | |
結果 | 11111111 |
- | 0101 |
xor | 0011 |
-------- | |
結果 | 0110 |
巧用
void swap(int &a,int &b)
{
a=a^b;
b=b^a;
a=a^b;
}
a1=a^b
b=b^a1=b^a^b=a
//此時a1=a^b b=a
a=a1^a=a^b^a=b
a=a^b^(b=a);//此類形式是不正確的UB行為,在不同編譯器中會有不同的結果,切勿使用