Search code examples
javascriptarraysbinarydecimalparseint

printing decimal to binary in javascript


I am having trouble with some code where the function is meant to convert the decimal numbers to binary from an array. I am using parseInt to do the conversions but it only prints the first number and more often prints NaN. My goal is to print all the binary equivalent of the decimal numbers on a html page.

Here is my code:

function decimal_table ()
  {
    // real_array stores decimal numbers.

    const real_array = [];
    const binary_array = [];

       for (let i = 0; i <= 50; i++)
      {
        real_array.push(i);
        document.getElementById("numbers").innerHTML = real_array.join(" ");
      }

       for (let b = 0; b <= 50; b++)
      {
        let calc = parseInt(real_array[b], 2);
        binary_array.push(calc);
        document.getElementById("binaries").innerHTML = binary_array.join(" ");
      }
  }

I want the output to look like this:

0 0000
1 0001
2 0010
3 0011
4 0100

and so on.


Solution

  • You may have a look to

    parseInt(real_array[b], 2);
    

    where you have a number which contains digits who are not parsable by having a radix of two.

    As example take 2 and perform parseInt(2, 2).

    The result is NaN, because 2 is not a binary number, because binary numers have only digits of zero and one.

    Beside that, it is the wrong direction, binary → decimal, but you need decimal → binary.


    You need to take Number#toString with a base of two and pad the start with zeroes.

    You could take a single loop and add the values to the array.

    After the loop make the assignment to the elements.

    function decimal_table() {
        const real_array = [];
        const binary_array = [];
    
        for (let i = 0; i <= 50; i++) {
            real_array.push(i);
            binary_array.push(i.toString(2).padStart(8, 0));
        }
    
        document.getElementById("numbers").innerHTML = real_array.join(" ");
        document.getElementById("binaries").innerHTML = binary_array.join(" ");
    }
    
    decimal_table();
    <div id="numbers"></div>
    <div id="binaries"></div>