4

Possible Duplicate:
What does the ^ operator do?

>>> var foo = [1,2]
>>> var bar = [3,4]
>>> foo ^ bar
0
>>> foo ^ 3
3
>>> 1^3
2

What is the purpose of the operator: ^?

Edit 1: Can you explain why

>>> foo ^ bar
0

?

Community
  • 1
  • 1
JohnJohnGa
  • 15,446
  • 19
  • 62
  • 87

3 Answers3

6

In the case of 1^3, the XOR operator does some binary stuff to get 2.

    1 = 00000001 ^
    3 = 00000011
        ========
        00000010 = 2

JavaScript sees the array syntax [x,y] as NaN when you start doing math-y things with it. NaN is interpreted as 0 when you do bitwise operations on it, so the foo and bar math starts to make sense taking that into account:

foo => NaN = 00000000 ^
bar => NaN = 00000000
             ========
             00000000 = 0

foo => NaN = 00000000 ^
         3 = 00000011
             ========
             00000011 = 3

Which seems to hold true. [1,2]^7 = 7, [1,2,3]^9 = 9, etc.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • 3
    What about XOR with foo & bar? – hungryMind Oct 20 '11 at 12:31
  • @hungryMind: `+[1,2]` is `NaN`, and `NaN ^ 3` is `3`, because `NaN` will be converted to `0` in the `ToInt32` operation as defined in section 11.10 of the ECMAScript specification. – pimvdb Oct 20 '11 at 12:36
  • That's the answer he was expecting I think. Anyone can easily find details of XOR, but operator between array and number was his concern. Thanks for clarification – hungryMind Oct 20 '11 at 12:38
3

Bitwise XOR

usoban
  • 5,428
  • 28
  • 42
1

Its called one of Bitwise operator,it treat their operands as a sequence of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers.Bitwise XOR (a ^ b) Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.

EDIT:

a b a XOR b 
0 0 0 
0 1 1 
1 0 1 
1 1 0 

and also

 9 (base 10) = 00000000000000000000000000001001 (base 2)
 14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
  • I think you should at least state *where* you copied/pasted this from. – pimvdb Oct 20 '11 at 12:40
  • I don't mind but your sentence doesn't read pretty. Anyway, it's surprising they put the exact same example and sentence from your book on https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators :) – pimvdb Oct 20 '11 at 12:46
  • @pimvdb, sorry for saying like that in my last comment but I have seen in one of my book given by my lecturer. – Sai Kalyan Kumar Akshinthala Oct 20 '11 at 12:51