How does the bitwise operator XOR ('^') work? How does the bitwise operator XOR ('^') work? php php

How does the bitwise operator XOR ('^') work?


^ 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 = 11 ^ 1 = 00 ^ 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.


This looks like swapping a value using XOR. Though I am not sure about the strings in PHP (normally you use it for ints or something). For a truth table of XOR you can look here.

The interesting thing about XOR is that it is reversable: A XOR B XOR B == A ... that is not working with AND or OR. Because of this fact, it can be used as in your example to swap two values:

$x ^= $y;$y ^= $x;$x ^= $y;

means:

$x = $x ^ $y$y = $y ^ ($x ^ $y)                // = $x$x = ($x ^ $y) ^ ($y ^ ($x ^ $y))  // = $y


In this example, when you're using ^ characters, they are casted to integers. So

"a" ^ "b"

is the same as:

ord("a") ^ ord ("b")

with one exception. In the first example, the result was casted back to a string. For example:

"a" ^ "6" == "W"

because of:

ord("a") ^ ord("6") == 87

and

chr(87) == "W"