JavaScript: To Binary String

Number.prototype.toString()

numObj.toString([radix]) // valid radix 2 to 36, default to 10 if missing
> Number(21).toString(2)
'10101'

> let a = 20
> a.toString(2)
'10100'

Custom Function

function toBinaryString(n) {
  let b = 0; // value in decimal
  let i = 1; // i will be 1, 10, 100, 1000 etc.

  while (n != 0) {
    let rem = n % 2; // 0 or 1
    b = b + (rem * i);
    i = i * 10;          // shift 1 position to the left by 1 in decimal format
    n = parseInt(n / 2); // shift 1 bit to the right by 1 in binary format
  }
  return String(b);
}
function toBinaryString(n) {
  let b = [];
  // b will have bit in least to most significant order
  while (n) {
    // n & 1 is either 0 or 1 of the least significant bit
    b.push(n & 1); 
    // n >> 1 is right shift by 1 or dividing n by 2 or removing least significant bit
    n = n >> 1; 
  }
  b = b.reverse(); // to most to least significant order
  return b.reduce((acc, v) => acc + '' + v, ''); // list to string
}

Leave a Comment

Your email address will not be published. Required fields are marked *