The JavaScript Bitwise Operators perform bit operations. All the decimal values are converted into binary values (sequence of bits, i.e., 0100, 1100, 1000, 1001, etc.). Next, the JavaScript bitwise operator will work on these bits, such as shifting them from left to right or converting bit values from 0 to 1, etc.
The below table shows the different JavaScript Bitwise operators and their meanings. For example, Consider x = 6 and y = 8 and their values in binary form are: x = 0110 and y = 1000
JavaScript Bitwise Operators | Meaning | Examples |
---|---|---|
& | Bitwise AND | X & Y = 0000 |
| | Bitwise OR | X | Y = 1110 |
^ | exclusive OR | X ^ Y = 1110 |
~ | complement | ~X = 00001001 (Not operator will convert all 0 into 1.) |
<< | Shift left | X << 1 = 00001100 (Bits will move 1 step left. If we use 2 or 3 then they shift accordingly) |
>> | Shift right | Y >> 1 = 00000100 |
Let us see the Truth Table behind JavaScript Bitwise Operators.
x | y | x & y | X | y | x ^ y |
---|---|---|---|---|
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 0 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
JavaScript Bitwise Operators Example
Let us see one example for a better understanding. For this JavaScript bitwise operators example, we use two variables, a and b; their values are 9 and 65. We are going to use these two variables to show you various Bitwise operations
<!DOCTYPE html> <html> <head> <title> JavaScriptBitwiseOperators </title> </head> <body> <h1> JavaScriptBitwiseOperators </h1> <script> var a = 9, b = 65; document.write("Bitwise AND Operator a & b = " + (a&b)); document.write("<br \> Bitwise OR Operator a | b = " + (a|b)); document.write("<br \> Bitwise EXCLUSIVE OR Operator a^b = " + (a^b)); document.write("<br \> Bitwise NOT Operator ~a = " + (~a)); document.write("<br \> LEFT SHIFT Operator a << 1 = " + (a << 1)); document.write("<br \> RIGHT SHIFT Operator b >> 1 = " + (b >> 1)); </script> </body> </html>
In this JavaScript Bitwise Operators program, we declared 2 integers, a and b, and assigned the values 9 and 65. The binary form of 9 = 0001001 and 65 = 1000001.
The document write statements will perform the bitwise operations on a and b, and then they will display the output. Let us see the JavaScript calculations
AND Operation = a&b
0001001 & 1000001 = 0000001 = 1
OR Operation = a || b
0001001 || 1000001 = 1001001 = 73
Exclusive OR Operation = a^b
0001001 ^ 1000001 = 1001000 = 72
JavaScript bitwise Left Shift Operator operation: Left Shifting one position equals multiplying the number by 2. It means,
a << 1 = (9 * 2) = 18
If we say, a<<2, then multiply the number with 4, and so on
OR
a << 1 = 0001001 << 1 = 0010010 = 18
Right Shift Operation = b>> 1
1000001 >> 1 = 0100000 = 32