You are currently viewing Bitwise Operator in JavaScript | Beginners Guide

Bitwise Operator in JavaScript | Beginners Guide

Bitwise Operator in Javascript

Bitwise operators are used to performing operations on bits. So, in this article, we will see about the bitwise operator in javascript. It converts the given decimal number to its binary equivalent number, and then they perform the operations on bits of those binary equivalent numbers.

Types of Bitwise operators

They are different bitwise operators provided by the javascript. There are:

&: Bitwise AND operator

If both LHS and RHS are 1 then the result will be 1`, in all other cases result will be 0.

Ex:

document.write(1 & 1, "<br/>"); // output: 1

|: Bitwise OR operator

If both LHS and RHS are 0 then the result will be 0, in all other cases result will be 1.

Ex:

document.write(0 | 0, "<br/>"); // output: 0

^: Bitwise Exclusive or operator

If both LHS and RHS are the same then the result will be 0, otherwise, the result will be 1.

Ex:

document.write(1 ^ 0, "<br/>"); // output: 1

~: Bitwsie Complement operator

If the given operand is a positive integer, then add 1 and change the sign
If the given operand is a negative integer, then subtract 1 and change the sign.

Ex:

document.write( ~3, "<br/>"); // output: -4

<<: Bitwise Left shift operator

Shifts the bits of the first number to the left by the number of positions indicated by the second number

Ex:

document.write( 8<<6, "<br/>");  // output: 512

>>: Bitwise Right shift operator

Shifts the bits of the first number to the right by the number of positions indicates by the second number

READ ALSO  2 Simple ways to Compare two Arrays in JavaScript

Ex:

document.write( 16>>4, "<br/>");  // output: 1

Leave a Reply