Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XOR operation in C++

Tags:

c++

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

For instance, 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 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.

like image 225
Bak1139 Avatar asked Sep 28 '13 13:09

Bak1139


People also ask

What is a XOR operation?

The XOR logical operation, exclusive or, takes two boolean operands and returns true if, and only if, the operands are different. Conversely, it returns false if the two operands have the same value.

What is the use of XOR in C++?

There is a somewhat unusual operator in C++ called bitwise EXCLUSIVE OR, also known as bitwise XOR. (In English this is usually pronounced "eks-or".) The bitwise XOR operator is written using the caret symbol ^ . A bitwise XOR operation results in a 1 only if the input bits are different, else it results in a 0.

What is Bitwise operator in C language?

What is a Bitwise Operator? The Bitwise Operator in C is a type of operator that operates on bit arrays, bit strings, and tweaking binary values with individual bits at the bit level. For handling electronics and IoT-related operations, programmers use bitwise operators. It can operate faster at a bit level.


2 Answers

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

First 1 ^ 3 is evaluated

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)

0 0 1 0 // 2  

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

The result is 5.

like image 83
Banex Avatar answered Oct 20 '22 21:10

Banex


1 ^ 3 ^ 7 is not a function of three arguments, it is: (1 ^ 3) ^ 7 which equals 2 ^ 7 which 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.

like image 34
aschepler Avatar answered Oct 20 '22 22:10

aschepler