How to use Right Shift Operator In Javascript
This approach uses the right shift operator (>>) to determine if a specific bit is set in a given number.
- At first we apply (number >> bitPosition) , this operation shifts the binary representation of the number to the right by bitPosition positions.
- Then we perform (number >> bitPosition) & 1 == 1 , which is used to check if the bit at the specified position in the binary representation of the number is set (i.e., equals 1).
Example: This example shows the implementation of the above approach.
function isBitSetApproach1(number, bitPosition) {
return ((number >> bitPosition) & 1) === 1;
}
const num = 5; // 101 in binary
console.log(isBitSetApproach1(num, 0));
console.log(isBitSetApproach1(num, 1));
console.log(isBitSetApproach1(num, 2));
Output
true false true
Check if a given Bit is Set or Not using JavaScript
Bits in a number are fundamental components of binary representation and each bit in binary has only two states like 0 or 1. With the help of those two bits, we can represent any number in a binary format. And if a bit is to be set if it’s value is 1 otherwise it is not set.
Note: Indexing starts with 0 from LSB (least significant bit) side in the binary representation of the number.
Example:
Input: n = 5, bit_position = 1
Output: false
Input: n = 6, bit_position = 2
Output: true
Below are the approaches to check if a given bit is set or not in JavaScript:
Table of Content
- Using Left Shift Operator
- Using Right Shift Operator