Open In App

JavaScript Program to Extract the Leftmost Set Bit of a Given Integer

Last Updated : 10 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given an integer value the task is to extract the leftmost set bit of a given integer in JavaScript. The leftmost set bit is a bit whose value is 1 and is present at the leftmost position in binary representation.

The below approaches can be implemented to extract the leftmost set bit.

Using Bitwise Operations

In this approach, we will use the left shift (<<) and unsigned right shift (>>>) bitwise operations to initialize and update a mask (res) with the leftmost set bit of the given integer num. The while loop checks and shifts the mask until it aligns with the leftmost set bit in num, resulting in res containing only the leftmost set bit value.

Syntax:

x << y

Example: The below example uses Bitwise Operations to extract the leftmost set bit of a given integer in JavaScript.

JavaScript
let num = 18;
let res = 1 << 31;
while ((res & num) === 0) {
    res = res >>> 1;
}
console.log(res);

Output
16

Using Logarithms

In this approach, we are using logarithms (Math.log2) to find the position of the leftmost set bit in the given integer, and then using Math.pow to calculate the value of that bit, resulting in res containing only the leftmost set bit value.

Syntax:

Math.log2(x)

Example: The below example uses Logarithms to extract the leftmost set bit of a given integer in JavaScript.

JavaScript
let num = 40;
let res = Math.pow(2, 
    Math.floor(Math.log2(num)));
console.log(res); 

Output
32

Using Binary String Conversion

In this approach, we are using binary string conversion (toString(2)) to represent the integer number in binary form. Then, we calculate the position of the leftmost set bit by finding the index of the rightmost ‘1’ in the binary string. Finally, we use a bitwise left shift (<<) to create a mask (res) with only the leftmost set bit value.

Syntax:

num.toString(2)

Example: The below example uses Binary String Conversion to extract the leftmost set bit of a given integer in JavaScript.

JavaScript
let num = 9; 
let bStr = num.toString(2);
let lSetBitPos = 
    bStr.length - 1 - bStr.
        indexOf('1');
let res = 1 << lSetBitPos;
console.log(res); 

Output
8

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads