0

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?

3 Answers3

3

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      |
+---+---+--------+
Spoody
  • 2,657
  • 1
  • 21
  • 34
1

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.
Wai Ha Lee
  • 7,664
  • 52
  • 54
  • 80
Joel Smith
  • 86
  • 3
  • 3
1
12  = 1100
09  = 1001
Xor = 0101 = 5

Exclusive or means only 1 bit at the same position to be high.

DigiLive
  • 1,022
  • 1
  • 12
  • 21