How to use Bitwise XOR operator in Javascript
Description
The bitwise XOR operator is represented by a caret ^
and
works on two values.
Here is the truth table for bitwise XOR:
BIT FROM FIRST NUMBER | BIT FROM SECOND NUMBER | RESULT |
---|---|---|
1 | 1 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
Bitwise XOR returns 1 only when exactly one bit has a value of 1, if both bits contain 1, it returns 0.
Example
var result = 25 ^ 3;
console.log(result); //26
Actual calculation
25 = 0000 0000 0000 0000 0000 0000 0001 1001
3 = 0000 0000 0000 0000 0000 0000 0000 0011
---------------------------------------------
XOR = 0000 0000 0000 0000 0000 0000 0001 1010
The code above generates the following result.