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.
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.
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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With