Hi i was just wondering if someone can explain to me how the following php code evaluates to 5
<?php
$a = 12 ^ 9;
echo $a;
?>
so I know the output will be 5, but can someone explain to me how this works?
Hi i was just wondering if someone can explain to me how the following php code evaluates to 5
<?php
$a = 12 ^ 9;
echo $a;
?>
so I know the output will be 5, but can someone explain to me how this works?
The ^
operator as you say is bitwise, so it converts the integer to a binary value.
12
is 00001100
in binary.
9
is 00001001
in binary.
A: 00001100 12
XOR(^)
B: 00001001 9
---------
Output: 00000101 5
It is simply 1
if only one of the inputs is 1
, here is the truth table for XOR:
+---+---+--------+
| A | B | Output |
+---+---+--------+
| 0 | 0 | 0 |
+---+---+--------+
| 0 | 1 | 1 |
+---+---+--------+
| 1 | 0 | 1 |
+---+---+--------+
| 1 | 1 | 0 |
+---+---+--------+
As far as I understand the process, php converts the numbers into binary and performs an XOR operation on them.
12 -> 1100
9 -> 1001
1100 XOR 1001 = 0101 = 5.
12 = 1100
09 = 1001
Xor = 0101 = 5
Exclusive or means only 1 bit at the same position to be high.