How to use Bitwise Operations In Javascript
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.
let num = 18;
let res = 1 << 31;
while ((res & num) === 0) {
res = res >>> 1;
}
console.log(res);
Output
16
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