How to use Bitwise AND operator in Javascript
Description
The bitwise AND operator is represented by the ampersand character &
and works on two values.
Bitwise AND uses the rules in the following truth table to perform an AND operation between the two bits in the same position.
BIT FROM FIRST NUMBER | BIT FROM SECOND NUMBER | RESULT |
---|---|---|
1 | 1 | 1 |
1 | 0 | 0 |
0 | 1 | 0 |
0 | 0 | 0 |
The result will be 1 only if both bits are 1. If either bit is 0, then the result is 0.
Example
var result = 25 & 3;
console.log(result); //1
The actual calculation.
25 = 0000 0000 0000 0000 0000 0000 0001 1001
3 = 0000 0000 0000 0000 0000 0000 0000 0011
---------------------------------------------
AND = 0000 0000 0000 0000 0000 0000 0000 0001
The code above generates the following result.