XOR运算符的意义

6

嘿,有人能解释一下XOR运算符的重要性以及我们可以使用它解决哪些问题吗?如果有人能列出我们可以使用XOR运算符解决哪些类型的问题,那将非常有帮助。

提前感谢。


1
这就像是要求列出可以用加法解决的问题列表一样。 - harold
2个回答

6

从XOR (^)的真值表开始:

x  y    x^y
0  0    0    
0  1    1
1  0    1
1  1    0

可以使用XOR解决的问题:

  1. 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
    
  2. 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
    
  3. 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.
    
  4. 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).

  5. 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).

  6. 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

1

了解异或:

请注意:

A^B=A'.B+B'.A

另外,正如名称所示

A^B=(A+B)%2

简单来说,按位异或对于相同的位返回1,对于不同的位返回0。

一般用途:

它可以应用于任何地方,只要您可以应用一个逻辑,使得相等的组件/成对组件会相互抵消。

例如:有一个问题,需要查看哪个鞋子是不完整的。你通过整数给出鞋子类型。你可以这样做:

xor=0

循环n次:

xor^=shoe_type;

其中,在大多数编程语言中,^ 是XOR运算符。

在这里,仅保留以单个数量存在的整数,而成对存在的整数被计算为零,因为 a^a=0;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接