嘿,有人能解释一下XOR运算符的重要性以及我们可以使用它解决哪些问题吗?如果有人能列出我们可以使用XOR运算符解决哪些类型的问题,那将非常有帮助。
提前感谢。
嘿,有人能解释一下XOR运算符的重要性以及我们可以使用它解决哪些问题吗?如果有人能列出我们可以使用XOR运算符解决哪些类型的问题,那将非常有帮助。
提前感谢。
从XOR (^)的真值表开始:
x y x^y
0 0 0
0 1 1
1 0 1
1 1 0
可以使用XOR解决的问题:
Comparison of 2 Boolean Functions x
and y
.
If x and y are same then x ^ y = 0
If x and y are different then x ^ y = 1
Finding whether the number of ones ('1') in a binary representation of byte or integer is odd or even.
unsigned char a = 10; //in binary representation 00001010 (even number of 1s)
unsigned char b = 11; //in binary representation 00001011 (odd number of 1s)
Simply XORing all the bits will give:
* result = 1, if number of bits is odd
* result = 0, if number of bits is even
Using {Point 2.} the Parity (Parity Bit) of data bits can be found.
If even parity is required(i.e the data bits should have even number of 1s) then
if all the bits are XORed and if it gives the result 1 then
**Parity Bit = 1** else **Parity Bit = 0**.
Similar case can be made if odd parity of data bits are required.
In Proposition Logic if and only if (shortened iff) is a biconditional logical connective
and this iff
can be evaluated using XNOR
or ~XOR
(i.e negation of XOR).
If a equation involving 2 Boolean Functions A
and B
such as {A'.B + A.B'}
is encountered then this equation reduces to A ^ B
. Solving {A'.B + A.B'}
using primitive operators (AND(.), OR(+) and NEGATION(')) will result in 5 operations which can be reduced to 1 operation using XOR(^)
. Simply because A^B = A'.B + A.B'
. If the equation encountered is {A'B' + AB}
then {A'B' + AB}
= ~XOR
(i.e XNOR or negation of XOR).
If a particular bit in data needs to be inverted (i.e 1 to 0 or 0 to 1) then simply XORing that bit with 1
would achieve the purpose.
data = 1010;
^^^^
0001 (inverting the LSB, first bit from right)
---------------
result = 1011
x^y = sum (mod 2)
**。 - Archisman Pathak请注意:
A^B=A'.B+B'.A
另外,正如名称所示
A^B=(A+B)%2
简单来说,按位异或对于相同的位返回1,对于不同的位返回0。
它可以应用于任何地方,只要您可以应用一个逻辑,使得相等的组件/成对组件会相互抵消。
例如:有一个问题,需要查看哪个鞋子是不完整的。你通过整数给出鞋子类型。你可以这样做:
xor=0
循环n次:
xor^=shoe_type;
其中,在大多数编程语言中,^ 是XOR运算符。
在这里,仅保留以单个数量存在的整数,而成对存在的整数被计算为零,因为 a^a=0;