Javascript Bitwise Operator AND

Introduction

The bitwise AND operator is the ampersand character (&) and works on two values.

The bitwise AND lines up the bits in each number and use the rules in the following truth table, performs 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

A bitwise AND operation returns 1 if both bits are 1.

It returns 0 if any bits are 0.

As an example, to AND the numbers 25 and 3 together, use the following code:

let result = 25 & 3; 
console.log(result);  // 1 

The result of a bitwise AND between 25 and 3 is 1. Take a look:

And operation:

 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 

As you can see, only bit 0 contains a 1 in both 25 and 3.

Because of this, every other bit of the resulting number is set to 0, making the result equal to 1.


// Here is a 32 bit representation of numbers
// 11 = 00000000000000000000000000001011
//  6 = 00000000000000000000000000000110
//  2 = 00000000000000000000000000000010

let a = 11 & 6;

console.log(a); // 2



PreviousNext

Related