Using Bitwise operators in JavaScript
Introduction
Though bitwise operators in Javascript hardly get any attention, they are actually very powerful and have a wide variety of usage. They are considered for faster numerical calculations and conversions. We can leverage them to replace certain complex coding scenarios and make our code more readable.
By the end of this tutorial, you get a basic understanding of bitwise operators, what they are, and how to use them.
Prerequisites
Conceptual Prerequisites
- Very basic understanding about what is binary.
- How the logical “and” and “or” operators work and the outcomes of using them.
- Understanding of operators and operands.
Technical Prerequisites
How binary works in Javascript
As bitwise operators work at binary level, it’s essential to understand what JavaScript provides for binary conversion. Believe me, it is much simpler than it sounds.
We can convert any number to a string using the toString() function as shown below:
var n = 2;
console.log(n.toString());
Output
2
The toString function has one argument (called radix) which can be used to specify the base. The base determines the target conversion. You can pass “2” to get binary, “8” to get octal, and “16” to get the hexadecimal value of the number being converted. By default it is 10 and thus returns the decimal value.
var num = 18;
var binaryText = num.toString(2);
console.log(binaryText);
Output
10010
As we can see, the number 18 got converted into a binary string – 10010.
Tip: To do the reverse (getting number from binary string) we can use
parseInt("binary_string",2);
So, in our case, to convert “10010” to number 18, we can use the following code:
var num = 18;
var binaryText = num.toString(2);
console.log(binaryText);
console.log(parseInt(binaryText));
Output
10010
18
This covers the very basics of how binary conversion works in JavaScript. We can work with bitwise operators without actually knowing the binary conversion. However, we may not be able to understand how the result of the bitwise operator gets calculated. Let’s see this in action.
Using Bitwise Operators
For this tutorial, let’s consider basic numbers for bitwise operations. The numbers we are going to use will be 1, 2, and 3. Here is the list of binary numbers for each of them.
- 1 → 001
- 2 → 010
- 3 → 011
Note: The actual binary string will have 63 0s and 1 in the end to constitute 64 bit binary representation. However, for simplicity we are just taking the last 3 digits.
Bitwise AND (&)
The bitwise AND operator can be used using a symbol “&” (note that we use double “&” for logical AND operations among non-binary variables)
Here is what “&” returns for bits:
- 0 & 0 = 0
- 1 & 0 = 0
- 1 & 1 = 1
This is very similar to our logical AND operation – If both the conditions are true then return true otherwise return false. In this case, the true is replaced by 1 and 0 equals to false.
JavaScript generates the resulting binary number by comparing each binary bit. The table below shows the bitwise AND between number 1 and 3.
Number | Binary equivalent | Binary Bits | ||
---|---|---|---|---|
1 | 001 | 0 | 0 | 1 |
& | & | & | & | & |
3 | 001 | 0 | 1 | 1 |
Result = 1 | 0 & 0 = 0 | 0 & 1 = 0 | 1 & 1 = 1 |
If we convert the resulting string 001 to decimal then we will get “1” as output. So, “1” & “3” results in “1”. Internally, JavaScript recognizes the bitwise operator and converts 1 and 3 into binary format and applies bitwise AND for each bit and converts the resulting binary string to decimal number. You can quickly try this in your browser console by hitting F12 and typing:
console.log(1&3);
Bitwise OR (|)
The Bitwise OR uses single symbol “|”.
Here is what “|” returns for bits:
- 0 | 0 = 0
- 1 | 0 = 1
- 1 | 1 = 1
This is similar to logical OR operation – where if any one condition is true then return true otherwise return false. In this case, the true is replaced by 1 and 0 equals to false.
The table below shows the Bitwise OR between number 1 and 3.
Number | Binary equivalent | Binary Bits | ||
---|---|---|---|---|
1 | 001 | 0 | 0 | 1 |
| | | | | | | | | |
3 | 011 | 0 | 1 | 1 |
Result = 3 | 0 | 0 = 0 | 0 | 1 = 0 | 1 | 1 = 1 |
If we convert the resulting string 011 to decimal then we will get “3” as output. So, “1” | “3” results in “3”. Internally, JavaScript recognizes the bitwise operator and converts 1 and 3 into binary format and applies bitwise OR for each bit and converts the resulting binary string to decimal number.
Bitwise XOR (^)
The symbol for bitwise XOR is “^”.
Here is what “^” returns for bits:
- 0 ^ 0 = 0
- 1 ^ 0 = 1
- 1 ^ 1 = 0
The rule for XOR (exclusive OR) is that if both bits are different then return “1” else “0”. The XOR between 1 and 3 would return 2. Here is the explanation:
Number | Binary equivalent | Binary Bits | ||
---|---|---|---|---|
1 | 001 | 0 | 0 | 1 |
^ | ^ | ^ | ^ | ^ |
3 | 011 | 0 | 1 | 1 |
Result = 2 | 0 ^ 0 = 0 | 0 ^ 1 = 1 | 1 ^ 1 = 0 |
Bitwise Shift Left (<<)
Syntax: Number << Position
The left side number of the shift operator is the actual number and the right side of the operator is the position. For example, “5 << 2” tells Javascript to perform a shift left on number 5 for two positions. Here is how JavaScript actually performs the shift left operation.
- It converts the number to the binary equivalent. In our case, number 5 will be converted to binary form that is – 101.
- Adds two 00s to the right of the binary string. This will result in 10100 for number 5.
- Convert the binary string to a decimal number. In our case, it will be 20. So, js console.log(5<<2); will result in number 20.
Bitwise Shift Right (>>)
Syntax: Number >> Position
Shift right operator will remove binary numbers from right. How many numbers will be removed? As you might have guessed, the number mentioned as the position.
Here is an example. Let’s say we have 5 >> 2.
- JavaScript will convert 5 to binary equivalent. 101 in our case.
- Remove two numbers from the right side. This will result in 101.
- Convert the result into decimal. The result will be 1 in our case.
Conclusion
Bitwise operators sound very complex at the first, however, once we understand the basics, it is very simple. We can convert any number to binary using the “.toString(2)” method. The conversion will help to understand the output of the bitwise operator. All the bitwise operators work at the bit level after converting operands to binary format.
- Bitwise AND returns 1 if both the bits are 1 else 0.
- Bitwise OR returns 1 if at least one of the bits is 1 else 0.
- Bitwise XOR only returns 1 if both operands are different. Otherwise returns 0.
- Shift left adds 0s in the end mentioned in the second operand and shift right just removes bits mentioned as the second operands.
Hope this brief introduction helped to understand the bitwise operator and how its results are being calculated.