C++中的异或运算

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19067286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:28:39  来源:igfitidea点击:

XOR operation in C++

c++

提问by Bak1139

How does the XOR logical operator work on more than two values?

XOR 逻辑运算符如何处理两个以上的值?

For instance, in an operation such as 1 ^ 3 ^ 7?

例如,在诸如 1 ^ 3 ^ 7?

0 0 0 1 // 1

0 0 1 1 // 3

0 1 1 1 // 7

__

0 1 0 1 // 5

for some reason yields 0 1 0 1, where as it should have, as I thought, yielded: 0 1 0 0, since XOR is only true when strictly one of the operands is true.

出于某种原因产生 0 1 0 1,正如我所想的那样,它应该产生:0 1 0 0,因为 XOR 仅在操作数之一严格为真时才为真。

回答by Banex

Because of the operator precedence and because the xoris a binary operator, which in this case is left-to-right.

因为运算符的优先级,并且因为xor是一个二元运算符,在这种情况下是从左到右的。

First 1 ^ 3is evaluated

首先1 ^ 3是评估

0 0 0 1 // 1

0 0 1 1 // 3
-------
0 0 1 0 // 2

The result is 2, then this number is the first operand of the last xor operation (2 ^ 7)

结果是2,那么这个数就是最后一次异或运算的第一个操作数( 2 ^ 7)

0 0 1 0 // 2  

0 1 1 1 // 7
-------
0 1 0 1 // 5

The result is 5.

结果是 5。

回答by Peter G.

  1. XOR works bitwise, XORing each position separately
  2. XOR is commutative, so a^b = b^a
  3. XOR is associative, so (a^b)^c = a^(b^c)
  1. XOR 按位工作,分别对每个位置进行异或
  2. XOR 是可交换的,所以 a^b = b^a
  3. XOR 是关联的,所以 (a^b)^c = a^(b^c)

Using this, a human can count the number of ones in a given position and the result bit is set exactly for an odd number of ones in the given position of the operands.

使用它,人们可以计算给定位置中 1 的数量,并且结果位被精确设置为操作数给定位置中的奇数个 1。

Counting ones yields (0101)binary=5

计数产生 (0101)binary=5

回答by aschepler

1 ^ 3 ^ 7is not a function of three arguments, it is: (1 ^ 3) ^ 7which equals 2 ^ 7which equals 5.

1 ^ 3 ^ 7不是三个参数的函数,它是: (1 ^ 3) ^ 7which equals 2 ^ 7which equals 5

Though actually this ^operator is associative: each bit in the result will be set if and only if an odd number of the operands had the bit set.

虽然实际上这个^运算符是关联的:当且仅当奇数个操作数设置了该位时,结果中的每个位才会被设置。

回答by Luchian Grigore

The expression is parsed as (1 ^ 3) ^ 7so you first get

表达式被解析为(1 ^ 3) ^ 7所以你首先得到

 0001 ^ 0011 

which is 0010. The rest is

这是0010. 剩下的就是

 0010 ^ 0111

which is 0101

这是 0101

回答by john

^ is a binary operator. It doesn't work on all three numbers at once, i.e. it's (1^3)^7, which is:

^ 是一个二元运算符。它不能同时处理所有三个数字,即 (1^3)^7,即:

1 ^ 3 == 2

1 ^ 3 == 2

2 ^ 7 == 5

2 ^ 7 == 5