0

I understand that for boolean values Exclusive OR says the output will be on if the inputs are different. link

But how does it work on non boolean values like below. In C# or Javascript, how is its value "10" for below code. Can anyone explain this for me please?

  Console.WriteLine(9^3);
Kalyan
  • 307
  • 2
  • 14

2 Answers2

1

I get the impression you are thinking in purely logical terms, where the result must be true or false, 1 or 0. The ^ operator does act this way, but as a bitwise operator is does it per bit, one at a time, instead of on the whole value at once. It's not that 9 and 3 are both "true", and so the result must be false. It's that 9 is 1001 and 3 is 0011, and when you check each of the corresponding bits with xor you get 1010, which is 10:

  1001  (9)
^ 0011  (3)
------
  1010  (10)
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
1

Bitwise operators perform operation on the bits stored in the memory.

Hence take equalent binary value for each decimal number and perform the operation.

 9 ---Binary Value ---> 0000 1001
 3 ---Binary Value ---> 0000 0011
      Perform EXOR (^) ------------
                        0000 1010  ---- Decimal Value --> 10
Praveen N
  • 137
  • 1
  • 7