How to use Right Shift and Bitwise AND Operation In Javascript
With this approach, we generate the mask with a right shift compared to a left one. This approach works especially well when the LSB (least significant bit) is considered as the 0th bit.
Example: Implementation to check if the ith bit is set or not using right shift and bitwise AND operation.
function isIthBitSet(num, i) {
let mask = num >> i;
return (mask & 1) === 1;
}
console.log(isIthBitSet(7, 1));
Output
true
Time Complexity: O(1)
Space Complexity: O(1)
Check if the ith Bit is Set or Not using JavaScript
Checking if the ith bit is set or not in a binary representation is a common task in programming, especially in scenarios where bitwise operations are utilized. In this article, we’ll explore multiple approaches to accomplish this using JavaScript. Given a non-negative integer num and an index i, we need to determine whether the ith bit (from the right) of num is set (1) or not (0).
These are the following approaches:
Table of Content
- Using Bitwise AND Operation
- Using Right Shift and Bitwise AND Operation
- Using Bitwise Shift and Modulus Operator
Contact Us