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

前端 未结 6 484
粉色の甜心
粉色の甜心 2020-12-30 23:46

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
         


        
6条回答
  •  攒了一身酷
    2020-12-31 00:27

    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
    

提交回复
热议问题