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

前端 未结 6 493
粉色の甜心
粉色の甜心 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:24

    The ^ operator performs an XOR on the bit values of each variable. XOR does the following:

    a   = 1100
    b   = 1010
    xor = 0110
    

    x is the result of the XOR operation. If the bits are equal the result is 0 if they are different the result is 1.

    In your example the ^= performs XOR and assignment, and you swap the bits around between the two variables $x and $y.

    Read more here http://en.wikipedia.org/wiki/Xor_swap_algorithm

提交回复
热议问题