EN
JavaScript - bitwise AND operator
5
points
The main goal of this articleĀ is to show how bitwise AND operationĀ (&
operator) works on the JavaScript example.
The main concept of theĀ bitwise ANDĀ operationĀ is to make ANDĀ operations on each correspondingĀ bits.
Quick solution:
// ONLINE-RUNNER:browser;
const a = 3; // 0011
const b = 5; // 0101
const result = a & b; // <----- bitwise AND operation example
console.log(result); // 1 (in dec / base 10)
console.log(result.toString(2).padStart(4, '0')); // 0001 (in bin / base 2 )
Ā
The truth table for the AND operation is:Ā
a | b | a AND b (in JavaScript: a & b ) | JS Example |
0 | 0 | 0 | 0 & 0 === 0 |
0 | 1 | 0 | 0 & 1 === 0 |
1 | 0 | 0 | 1 & 0 === 0 |
1 | 1 | 1 | 1 & 1 === 1 |
So, the above table can be presented in JavaScript as:
// ONLINE-RUNNER:browser;
console.log(0 & 0); // 0
console.log(0 & 1); // 0
console.log(1 & 0); // 0
console.log(1 & 1); // 1
Ā
More complex example
// ONLINE-RUNNER:browser;
const a = 3; // 00000011
const b = 5; // 00000101
const result = a & b; // <----- bitwise AND operation example
// (in dec / base 10)
console.log(a); // 3
console.log(b); // 5
console.log(result); // 1
// (in bin / base 2 )
console.log(getBits(a, 8)); // 00000011
console.log(getBits(b, 8)); // 00000101
console.log(getBits(result, 8)); // 00000001
// Helpers:
function getBits(number, length) {
let text = '';
for (let i = length - 1; i > -1; --i) {
text += 0x01 & (number >> i);
}
return text;
}
Ā
Bitwise ANDĀ operation limitations
Hint: in JavaScript, bitwise AND 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:
3 (base 10) = 00000000000000000000000000000011 (base 2)
5 (base 10) = 00000000000000000000000000000101 (base 2)
--------------------------------
3 & 5 (base 10) = 00000000000000000000000000000001 (base 2) = 1 (base 10)
Ā
Features
1. bitwise AND operation is fast - easy to do by any CPU.