【问题标题】:Significance of XOR operatorXOR 运算符的意义
【发布时间】:2016-10-17 10:17:59
【问题描述】:

嘿,谁能解释一下 XOR 运算符的意义以及我可以使用它解决的所有问题。如果有人可以列出我们可以使用 XOR 运算符解决哪种类型的问题,那将非常有帮助。

提前致谢。

【问题讨论】:

  • 这就像要求一个可以通过加法解决的问题列表。

标签: bitwise-operators xor


【解决方案1】:

从异或的真值表(^)开始:

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

可以使用 XOR 解决的问题:

  1. 比较两个布尔函数xy

     If x and y are same then x ^ y = 0
     If x and y are different then x ^ y = 1
    
  2. 查找字节或整数的二进制表示中的个数('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
    
  3. 使用{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.
    
  4. 在命题逻辑中if and only if (shortened iff) is a biconditional logical connective 和这个iff 可以使用XNOR~XOR 进行评估(即XOR 的否定)。

  5. 如果遇到包含 2 个布尔函数 AB(例如 {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 的否定)。

  6. 如果需要反转数据中的特定位(即 1 到 0 或 0 到 1),那么只需将该位与 1 进行异或运算即可达到目的。

        data = 1010;
               ^^^^
               0001  (inverting the LSB, first bit from right)
      ---------------
      result = 1011 
    

【讨论】:

  • 作为上述伟大编译的扩展,异或运算符的物理意义在于x^y = sum (mod 2)
【解决方案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;

【讨论】:

    猜你喜欢
    • 2013-04-20
    • 2012-09-12
    • 2011-07-21
    • 2015-02-11
    • 2015-01-16
    • 2010-12-03
    • 2015-05-01
    • 2014-01-27
    • 1970-01-01
    相关资源
    最近更新 更多