Open In App

Check if a given Bit is Set or Not using JavaScript

Last Updated : 06 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Using Left Shift Operator

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.

JavaScript
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

Using Right Shift Operator

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.

JavaScript
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

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads