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

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

    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"
    

提交回复
热议问题