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

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

    ^ 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.

提交回复
热议问题