How to use Binary String Conversion In Javascript
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.
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
JavaScript Program to Extract the Leftmost Set Bit of a Given Integer
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.
Table of Content
- Using Bitwise Operations
- Using Logarithms
- Using Binary String Conversion
Contact Us