Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Read Bit Value, is single Bit On (1) or Off (0)?

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?

like image 458
Gil Epshtain Avatar asked Mar 30 '26 22:03

Gil Epshtain


2 Answers

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.

like image 115
Pointy Avatar answered Apr 02 '26 11:04

Pointy


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));
like image 37
Wais Kamal Avatar answered Apr 02 '26 12:04

Wais Kamal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!