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
?
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
?
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.
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)