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

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

    XOR or the exclusive or is based on logic and circuits. It indicates that, for example, A ^= B where A is 0111 and B is 0101 can be either 1 or 0 at each corresponding bit but not both. Therefore

    A = 0111
    B = 0101
        _____
    ^=  0010 
    

    To understand this better the rules of binary math apply except that there are no carry overs. So in binary math 1 + 0 = 1, 0 + 0 = 0, 0 + 1 = 1 and 1 + 1 = 0 (where a 1 is carried over to the next more significant position in binary math, but the XOR rules bypass this).

    Note: That the XOR rules, therefore, allow you to take the result of A ^= B in the example above and add A to it to get B or add B to it to get A (referencing the swap ability mentioned above.

提交回复
热议问题