How to use Bitwise XOR and Complement In Javascript
In this approach, we are using bitwise XOR (^) and a combination of bitwise AND (&) with subtraction (num – 1) to extract the rightmost set bit of the input number num. The expression (num & (num – 1)) effectively clears all bits to the right of the rightmost set bit, leaving only that bit intact for the XOR operation to isolate it.
Syntax:
let result = operand1 ^ operand2;
Example: The below example uses Bitwise Operations to extract the rightmost set bit of a given integer in JavaScript.
let num = 40;
let res = num ^ (num & (num - 1));
let position = Math.log2(res);
let output = position + 1;
console.log(output);
Output
4
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
Contact Us