How to use Bitwise Shift and Modulus Operator In Javascript
The approach involves shifting the given number num by i bits to the right, after which we evaluate if the result is odd or even by using the modulus operator. The ith bit is set if it is odd.
Example: Implementation to check if the ith bit is set or not using bitwise Shift and modulus operator.
function isIthBitSet(num, i) {
return (num >> i) % 2 === 1;
}
console.log(isIthBitSet(5, 1));
Output
false
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