【发布时间】:2016-10-17 10:17:59
【问题描述】:
嘿,谁能解释一下 XOR 运算符的意义以及我可以使用它解决的所有问题。如果有人可以列出我们可以使用 XOR 运算符解决哪种类型的问题,那将非常有帮助。
提前致谢。
【问题讨论】:
-
这就像要求一个可以通过加法解决的问题列表。
标签: bitwise-operators xor
嘿,谁能解释一下 XOR 运算符的意义以及我可以使用它解决的所有问题。如果有人可以列出我们可以使用 XOR 运算符解决哪种类型的问题,那将非常有帮助。
提前致谢。
【问题讨论】:
标签: bitwise-operators xor
从异或的真值表(^)开始:
x y x^y
0 0 0
0 1 1
1 0 1
1 1 0
可以使用 XOR 解决的问题:
比较两个布尔函数x 和y。
If x and y are same then x ^ y = 0
If x and y are different then x ^ y = 1
查找字节或整数的二进制表示中的个数('1')是奇数还是偶数。
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
使用{Point 2.}可以找到数据位的奇偶校验(奇偶校验位)。
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.
在命题逻辑中if and only if (shortened iff) is a biconditional logical connective 和这个iff 可以使用XNOR 或~XOR 进行评估(即XOR 的否定)。
如果遇到包含 2 个布尔函数 A 和 B(例如 {A'.B + A.B'})的方程,则该方程简化为 A ^ B。使用原始运算符(AND(.)、OR(+) 和 NEGATION('))求解 {A'.B + A.B'} 将产生 5 个运算,使用 XOR(^) 可以将其减少为 1 个运算。仅仅因为A^B = A'.B + A.B'。如果遇到的等式是{A'B' + AB},那么{A'B' + AB} = ~XOR(即XNOR 或XOR 的否定)。
如果需要反转数据中的特定位(即 1 到 0 或 0 到 1),那么只需将该位与 1 进行异或运算即可达到目的。
data = 1010;
^^^^
0001 (inverting the LSB, first bit from right)
---------------
result = 1011
【讨论】:
x^y = sum (mod 2)
注意:
A^B=A'.B+B'.A
顾名思义
A^B=(A+B)%2
简单来说,按位异或,相同位为 1,不同位为 0
它可以在任何地方使用,您可以在其中应用逻辑,使得相等的组件/组件对应该湮没。
例如一个问题,你可以看到哪双鞋是不完整的。给你一个整数类型的鞋子。 你可以这样做:
xor=0
n次:
xor^=shoe_type;
在大多数编程语言中,^ 是 XOR 的运算符。
在这里,只有单一数量的整数保留在我们的变量 xor 中,并且成对存在的整数被评估为零。因为 a^a=0;
【讨论】: