I'm a little confused when I see the output of following code:
$x = "a"; $y = "b"; $x ^= $y; $y ^= $x; $x ^= $y; echo $x; //Got b echo $y; //Got a
How does the operator ^
work here?
XOR in Python is also known as “exclusive or” that compares two binary numbers bitwise. If both bits are the same, the XOR operator outputs 0. If both bits are different, the XOR operator outputs 1. The Bitwise XOR sets the input bits to 1 if either, but not both, of the analogous bits in the two operands is 1.
To find XOR of more than two numbers, represent all numbers in binary representation, add 0's before if necessary. Write them like this. and so on. To find each bit of XOR just calculate number of 1's in the corresponding bits.
The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. The << (left shift) in C or C++ takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.
^ is the "exclusive or" bitwise operator. It reads in English as "either or". The result is 1 if and only if both bits differ:
1 ^ 0 = 1 1 ^ 1 = 0 0 ^ 0 = 0
Simplifying the example a bit so (and using Pseudo code):
$x = 0011 //binary $y = 0010 $x = $x xor $y //Result: x = 0001 //x = 0001 //y = 0010 $y = $y xor $x //Result: y = 0011 //x = 0001 //y = 0011 $x = $x xor $y //Result: x = 0010
All that PHP has done is treat the string "a" and "b" as their integer equivalents.
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