JS Bitwise Operators


JavaScript Bitwise Operators

Bitwise operators perform bit manipulations between two expressions of any of the data types of the integer data type category.

Bitwise operators convert two integer values to binary bits, and perform the ANDOR, XOR, or NOT, etc... operation on each bit, producing a result. Then converts the result to an integer/ decimal.

Ø  AND (&) If both bits are one, the result is one; otherwise, zero.

console.log (0 & 0); //0

console.log (0 & 1); //0

console.log (1 & 0); //0

console.log (1 & 1); //1

 

For Example:

let var1= 10;

let var2= 22;

console.log (var1 & var2); //Result =2

 

// Binary

10== 00001010

22== 00010110

 

// Bitwise AND Operation of 10 and 22

 

 00001010

&

 00010110

 

 00000010 == 2 // in Decimal 2

 

 

Note: Converting 10 to 32-bit binary gives us 00000000000000000000000000001010 and 22 gives 00000000000000000000000000010110. We have removed the preceding zeros for simplicity.

Ø  OR (|) If either bit is one, the result is one; otherwise, zero.

console.log(0 | 0); //0

console.log(0 | 1); //1

console.log(1 | 0); //1

console.log(1 | 1); //1

 

For Example,

let var1= 10;

let var2= 22;

console.log(var1 | var2); //Result =30

// Binary

10== 00001010

22== 00010110

 

// Bitwise AND Operation of 10 and 22

 

 00001010

|

 00010110

 

 00011110 == 30 // in Decimal 30

 

 

Ø  XOR (^) If bits are different, the result is one; otherwise, zero.

console.log (0 ^ 0); //1

console.log (0 ^ 1); //1

console.log (1 ^ 0); //1

console.log (1 ^ 1); //0

 

For Example:

let var20= 10;

let var30= 22;

console.log(var20 ^ var30); //Result =28

// Binary

10== 00001010

22== 00010110

 

// Bitwise AND Operation of 10 and 22

 

 00001010

^

 00010110

 

 00011101 == 28 // in Decimal 28

 

Ø  NOT (~) If the bit is zero, the result is one; otherwise, zero.

For Example:

let var1= 12;

let var2= 22;

console.log(~var1) //Result =-13

console.log(~var2); //Result =-23

 

When the bitwise NOT operation is performed, the binary result will be 11111111111111111111111111110011 which converts into the decimal value -13.

Remark: Bitwise NOT of a number x gives -(x + 1). Notice above ~12 gives -13.

Ø  Left shift (<<) Pushes zeros in from the right, and left most bits to fall off.

For Example,

let var1= 10;

let var2= 3;

console.log (var1 << var2); //Result =80

 

Ø  Right shift (>>) Pushes copies of left most bit in from left, right most bit falls off.

For Example,

let var1= 10;

let var2= 2;

console.log(var1 >> var2); //Result =2

 

Ø  Zero fill right shift (>>>) Pushes zeros in from left, and rightmost bits fall off.

For Example,

let var1= 10;

let var2= 2;

let var3= -3

console.log (var1 >>> var2); //Result =2

console.log (var2 >>> var3); //Result =0

 


Leave a comment
No Cmomments yet