1

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.

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the toString() method on the integer value with a radix (base) of 2 to get the binary representation.

Then you just pad the value.

const pad = (n, padding) => (padding + n).substr(-padding.length)

for (let i = 0; i < 8; i++) {
  console.log(pad(i, '  '), pad(i.toString(2), '0000'));
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/string-format/0.5.0/string-format.min.js"></script>


Here is a more advanced and self-documented version.

const isFunction = (fn) => fn && {}.toString.call(fn) === '[object Function]'
const pad = (n, padding) => (padding + n).substr(-padding.length)
const range = (min, max, step) => {
  if (max === undefined) { max = min; min = 0 }
  if (step === undefined) { step = 1 }
  return new Array(max - min).fill(0).map((_, i) => min + (isFunction(step) ? step(i) : (i * step)))
}

let start = 0
let end = 7
let base = 2
let binStep = n => Math.pow(base, n)                   // 2^n
let maxVal  = binStep(end)                             // 2^7 = 128
let maxLen  = Math.floor(Math.log10(maxVal)) + 1       // 3 (unused)
let decPad  = maxVal.toString(10).replace(/\d/g, ' ')  // '   '
let binPad  = maxVal.toString(2).replace('1', '0')     // '00000000'

range(start, end + 1, binStep)
  .forEach(n => console.log(pad(n, decPad), pad(n.toString(2), binPad)))
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/string-format/0.5.0/string-format.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.