Check if the ith Bit is Set or Not using JavaScript

Checking if the ith bit is set or not in a binary representation is a common task in programming, especially in scenarios where bitwise operations are utilized. In this article, we’ll explore multiple approaches to accomplish this using JavaScript. Given a non-negative integer num and an index i, we need to determine whether the ith bit (from the right) of num is set (1) or not (0).

These are the following approaches:

Table of Content

  • Using Bitwise AND Operation
  • Using Right Shift and Bitwise AND Operation
  • Using Bitwise Shift and Modulus Operator

Using Bitwise AND Operation

This approach checks if the ith bit is set by using the bitwise AND operator (&). If the ith bit is set, the result of the bitwise AND operation will be non-zero; otherwise, it will be zero.

Example: Implementation to check if the ith bit is set or not using bitwise AND operation.

JavaScript
function isIthBitSet(num, i) {
    let mask = 1 << i;
    // This line checks if the ith bit is set

    return (num & mask) !== 0;
}
console.log(isIthBitSet(5, 1)); 

Output
false

Time Complexity: O(1)

Space Complexity: O(1)

Using Right Shift and Bitwise AND Operation

With this approach, we generate the mask with a right shift compared to a left one. This approach works especially well when the LSB (least significant bit) is considered as the 0th bit.

Example: Implementation to check if the ith bit is set or not using right shift and bitwise AND operation.

JavaScript
function isIthBitSet(num, i) {
    let mask = num >> i;
    return (mask & 1) === 1;
}
console.log(isIthBitSet(7, 1)); 

Output
true

Time Complexity: O(1)

Space Complexity: O(1)

Using Bitwise Shift and Modulus Operator

The approach involves shifting the given number num by i bits to the right, after which we evaluate if the result is odd or even by using the modulus operator. The ith bit is set if it is odd.

Example: Implementation to check if the ith bit is set or not using bitwise Shift and modulus operator.

JavaScript
function isIthBitSet(num, i) {
    return (num >> i) % 2 === 1;
}
console.log(isIthBitSet(5, 1)); 

Output
false

Time Complexity: O(1)

Space Complexity: O(1)


Contact Us