Search code examples
javascriptbinarybit-manipulationbitwise-operatorsbit

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?


Solution

  • 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));