JavaScript - bitwise XOR operator
The main goal of this article is to show how bitwise XOR operation (^
operator, called: Exclusive OR) works on the JavaScript example.
The main concept of the bitwise XOR operation is to make XOR operations on each corresponding bits.
Quick solution:
xxxxxxxxxx
const a = 3; // 0011
const b = 5; // 0101
const result = a ^ b; // <----- bitwise XOR operation example
console.log(result); // 6 (in dec / base 10)
console.log(result.toString(2).padStart(4, '0')); // 0110 (in bin / base 2 )
The truth table for the XOR operation is:
a | b | a XOR b (in JavaScript: a ^ b ) | JS Example |
0 | 0 | 0 | 0 ^ 0 === 0 |
0 | 1 | 1 | 0 ^ 1 === 1 |
1 | 0 | 1 | 1 ^ 0 === 1 |
1 | 1 | 0 | 1 ^ 1 === 0 |
So, the above table can be presented in JavaScript as:
xxxxxxxxxx
console.log(0 ^ 0); // 0
console.log(0 ^ 1); // 1
console.log(1 ^ 0); // 1
console.log(1 ^ 1); // 0
xxxxxxxxxx
const a = 3; // 00000011
const b = 5; // 00000101
const result = a ^ b; // <----- bitwise XOR operation example
// (in dec / base 10)
console.log(a); // 3
console.log(b); // 5
console.log(result); // 6
// (in bin / base 2 )
console.log(getBits(a, 8)); // 00000011
console.log(getBits(b, 8)); // 00000101
console.log(getBits(result, 8)); // 00000110
// Helpers:
function getBits(number, length) {
let text = '';
for (let i = length - 1; i > -1; --i) {
text += 0x01 & (number >> i);
}
return text;
}
Hint: in JavaScript, bitwise XOR works on 32-bit integers. If number is bigger, the most significant bits are dicarded to get 32-bit integer number - it means only bits indexed from 0 to 31 will be used.
So, the above table can be also written as:
xxxxxxxxxx
3 (base 10) = 00000000000000000000000000000011 (base 2)
5 (base 10) = 00000000000000000000000000000101 (base 2)
--------------------------------
3 ^ 5 (base 10) = 00000000000000000000000000000110 (base 2) = 6 (base 10)
1. bitwise XOR operation is fast - easy to do by any CPU.
2. bitwise XOR operation can be inverted - it means, we do not lose any information with that operation, e.g.
xxxxxxxxxx
const a = 3; // 0011
const b = 5; // 0101
const result = a ^ b;
const a2 = result ^ b; // <-------- bitwise XOR inversion: a achieved with b
const b2 = result ^ a; // <-------- bitwise XOR inversion: b achieved with a
console.log(a2); // 3 (0011)
console.log(b2); // 5 (0011)