Convert decimal to binary in javascript & reactjs – Code Example

To convert a decimal number to a binary number in javascript & reactjs, you can follow these steps –

  1. Take a empty string value to hold output.
  2. Run a loop till our decimal number is greater than 0.
  3. Take mod of decimal number by 2 and prepend it to output string.
  4. set decimal number equals to decimal number / 2

Code Example –

function decimalToBinary(x) {
  var parsed = parseInt(x, 10);
  if (isNaN(parsed)) { return 0; }
  
  hexstr = ""
  while(parsed > 0) {
  	hexstr = (parsed % 2) + hexstr
    parsed = parseInt(parsed / 2)
  }
  
  return hexstr;
}

console.log(decimalToBinary('56'));
// expected output: "111000"

Source: MSDN