Reputation: 9801
In JavaScript, how can I know if a single Bit is On (1) or Off (0)?
function isBitOn(number, index)
{
// ... ?
}
// Example:
let num = 13; // 1101
isBitOn(num, 0); // true 1
isBitOn(num, 1); // false 0
isBitOn(num, 2); // true 1
isBitOn(num, 3); // true 1
I know that in JavaScript we have Bitwise Operations. But How can I use them, or use any other method, the read single Bit?
Upvotes: 1
Views: 2367
Reputation: 6180
Convert the number to binary, then check the bits:
function isBitOn(number, index) {
let binary = number.toString(2);
return (binary[(binary.length - 1) - index] == "1"); // index backwards
}
let num = 13; // 1101
console.log(isBitOn(num, 0));
console.log(isBitOn(num, 1));
console.log(isBitOn(num, 2));
console.log(isBitOn(num, 3));
Upvotes: 2
Reputation: 413682
JavaScript retains the legacy of the C binary operators. You use the "index" to shift the value 1 to the left, and then you AND the result to the number you're interested in:
function isBitOn(number, index) {
return Boolean(number & (1 << index));
}
console.log(isBitOn(13, 0));
console.log(isBitOn(13, 1));
console.log(isBitOn(13, 2));
console.log(isBitOn(13, 3));
console.log(isBitOn(13, 4));
console.log(isBitOn(13, 5));
console.log(isBitOn(13, 6));
Note that that's the bitwise &
operator, and not the &&
short-circuit logical operator.
Also note that those operators treat the numbers as 32-bit integers, so it can't work for very large numbers.
Upvotes: 5