Binary array needs to have a fixed length

261 views Asked by At

I'm currently working on a binary-encoder which, when finished, should check certain checkboxes based on the decimal number that's entered.

I already have the script for converting the number to an array.
An output for the number 512 would be [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], which is want I want.
But an output for the number 4 would currently be [1, 0, 0], which I don't want to happen.
I want the array to have a fixed length, so the output for 4 should be [0, 0, 0, 0, 0, 0, 0, 1, 0, 0]

That's the code I currently have:

document.getElementById('myDez').oninput =
document.getElementById('myDez').onblur = document.getElementById('myDez').onkeydown = function (event) {  
    if (event.which == 13 || event.type == 'blur' || event.type == 'input') {
        var myDez = parseInt(this.value);
        var myBin = myDez.toString(2);
        document.getElementById('myBin').value = myBin;
        var arr = [,,,,];
        var arr =  myBin.split(''); 
        var numberArr = arr.map(Number); 

    }
    console.log(numberArr);

}

Thank you in advance.

2

There are 2 answers

0
ggorlen On BEST ANSWER

You can use padStart(10, 0) where 10 is the width you desire. Note that padStart will not truncate, so you can add slice(-width) if you want to ensure that large numbers don't exceed your desired width.

console.log([...(+"42").toString(2).padStart(10, 0)].map(Number));

Usage:

const decToBin = (n, width=10) => 
  (+n).toString(2).padStart(width, 0).slice(-width);

document.querySelector("input").addEventListener("keyup", e => {
  document.querySelector("div").textContent = decToBin(e.target.value);
});
<input type="number">
<div></div>

0
David D. On
var arr = new Array(10);
console.log(arr.length) // 10

That will create an array of fixed length.