Bitwise Operators


Bitwise Operators

The Bitwise operators in JavaScript work with operands in binary number (Base 2) format (in particular 32-bit integers), rather than decimal (Base 10), octal (Base 8), or hexadecimal (Base 16) notation. The binary equivalent of the decimal number ten, for example, is 1010. Bitwise operations on the operands of the operators in their binary representations are done in JavaScript, but the output is always in numerical value form.

In JavaScript, a bitwise operator transforms operands to their 32-bit signed integer form's 2's complement form. As a result, whenever an operator is used on an integer, the resulting value is the integer's 2's complement form.. The 1's complement of a number (i.e. bitwise Not of the number) plus 1 equals the 2's complement of an integer.

Operator Usage Description
Bitwise AND a & b It returns a one in each bit location if the bits of both the left and right operands are ones.
Bitwise OR a | b If either the left or right operand bits are one, this function returns a one in each bit.
Bitwise XOR a ^ b If bits of one but not both left and right operands are one, returns a one in a bit location.
Bitwise NOT ~ a The operand's bits are flipped.
Left shift a << b Shifts a by b bits to the left in binary form, shifting in zeros from the right.
Sign-propagating right shift a >> b Shifts a by b bits to the right in binary form, deleting bits shifted off.
Zero-fill right shift a >>> b Shifts a by b bits to the right in binary representation, deleting bits shifted off and shifting in zeros from the left.

Example No.1:

<html> <body> <h2>Knowledge2life</h2> <p id="demo">My First Paragraph.</p> <script> document.getElementById("demo").innerHTML = 5 & 1; </script> </body> </html>

OUTPUT:

Knowledge2life

1

Example No.2:

<html> <body> <h2>Knowledge2life</h2> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 | 1; </script> </body> </html>

OUTPUT:

Knowledge2life

5