To convert a decimal number to a binary number in javascript & reactjs, you can follow these steps –
- Take a empty string value to hold output.
- Run a loop till our decimal number is greater than 0.
- Take mod of decimal number by 2 and prepend it to output string.
- 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