How to use Left Shift Operator In Javascript
The isBitSet() function which takes two parameter like (number , bitPosition) and here we perform left shift operation to check if a specific bit is set (i.e., equals 1) in a given number.
This line first moves the binary representation of the number 1 to the left by bitPosition positions. Then, it performs a bitwise AND operation with the number, checking if the bit at the specified position in the number is set or not.
Example: This example shows the implementation of the above approach.
function isBitSet(number, bitPosition) {
return (number & (1 << bitPosition)) !== 0;
}
const num = 5; // 101 in binary
// Check if the least significant bit is set
console.log(isBitSet(num, 0));
// Check if the second least significant bit is set
console.log(isBitSet(num, 1));
// Check if the most significant bit is set
console.log(isBitSet(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