How to use Bitwise Shift and Loop In Javascript
In this approach, we are using bitwise left shift (<<) in a loop to create a mask that isolates the rightmost set bit of the input number num. The loop iteratively shifts the mask to the left until it aligns with the rightmost set bit in num, which is then extracted using the bitwise AND (&) operation.
Syntax:
while(condition) {
num <<=1
}
Example: The below example uses Bitwise Operations to extract the rightmost set bit of a given integer in JavaScript.
let num = 32;
let mask = 1;
while ((num & mask) === 0) {
mask <<= 1;
}
let position = Math.log2(mask);
let output = position + 1;
console.log(output);
Output
6
JavaScript Program to Extract the Rightmost set Bit of a Given Integer
We are given an integer value, the task is to extract the rightmost set bit of a given integer in JavaScript. The rightmost set bit is the bit whose value is 1 and appears first when reading the binary representation of a number from right to left.
The below approaches can be used to find the rightmost set bit in JavaScript.
Table of Content
- Using Bitwise Operations
- Using Bitwise XOR and Complement
- Using Bitwise Shift and Loop