XOR operation in C ++

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

For example, in an operation such as 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 gives 0 1 0 1, where, as I thought, it should turn out: 0 1 0 0, since XOR is true only if strictly one of the operands is true.

+4
source share
5 answers

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

First 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 operation xor ( 2 ^ 7)

0 0 1 0 // 2  

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

The result is 5.

+12
source
  • XOR works bitwise, XORing each position separately
  • XOR is commutative, therefore a ^ b = b ^ a
  • XOR , (a ^ b) ^ c = a ^ (b ^ c)

, , .

(0101) = 5

+4

1 ^ 3 ^ 7 : (1 ^ 3) ^ 7, 2 ^ 7, 5.

^ : , .

+4

(1 ^ 3) ^ 7,

 0001 ^ 0011 

0010.

 0010 ^ 0111

0101

+3

^ is a binary operator. It does not work in all three numbers at the same time, i.e. He (1 ^ 3) ^ 7, which is equal to:

1 ^ 3 == 2

2 ^ 7 == 5

0
source

All Articles