What is the purpose of the ^ operator?

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 

?

+4
source share
3 answers

In the case of 1^3 the XOR operator executes some binary data to get 2.

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

JavaScript sees the syntax of the [x,y] array as NaN when you start doing math things with it. NaN interpreted as 0 when you perform bitwise operations on it, so the math foo and bar starts to take into account the following:

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

This seems to be true. [1,2]^7 = 7 , [1,2,3]^9 = 9 , etc.

+6
source
+3
source

It is called one of the Bitwise operator, it processes their operands as a sequence of 32 bits (zeros and ones), and not as decimal, hexadecimal or octal numbers. As a result, XOR (a ^ b) returns one bit in each bit position, for which the corresponding bits of both, but not both operands are ones.

EDIT:

 aba XOR b 0 0 0 0 1 1 1 0 1 1 1 0 

and

  9 (base 10) = 00000000000000000000000000001001 (base 2) 14 (base 10) = 00000000000000000000000000001110 (base 2) -------------------------------- 14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10) 
+1
source

All Articles