Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 

How does the operator ^ work here?

like image 691
Young Avatar asked Apr 20 '10 12:04

Young


People also ask

How does XOR work in Python?

XOR in Python is also known as “exclusive or” that compares two binary numbers bitwise. If both bits are the same, the XOR operator outputs 0. If both bits are different, the XOR operator outputs 1. The Bitwise XOR sets the input bits to 1 if either, but not both, of the analogous bits in the two operands is 1.

How do you do XOR operations?

To find XOR of more than two numbers, represent all numbers in binary representation, add 0's before if necessary. Write them like this. and so on. To find each bit of XOR just calculate number of 1's in the corresponding bits.

What is the use of bitwise XOR operator in C?

The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. The << (left shift) in C or C++ takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.


1 Answers

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

like image 90
Yacoby Avatar answered Nov 03 '22 15:11

Yacoby