How to use Bitwise AND Operation In Javascript
This approach checks if the ith bit is set by using the bitwise AND operator (&
). If the ith bit is set, the result of the bitwise AND operation will be non-zero; otherwise, it will be zero.
Example: Implementation to check if the ith bit is set or not using bitwise AND operation.
function isIthBitSet(num, i) {
let mask = 1 << i;
// This line checks if the ith bit is set
return (num & mask) !== 0;
}
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