How can I convert (binary) integer into array?

Viewed 2566

I have the following form select field in my HTML code -

<select multiple class="form-control" name="uploadSites[]" id="uploadSitesDecoded">
    <option value="1">Site 1</option>
    <option value="2">Site 2</option>
    <option value="4">Site 3</option>
    <option value="8">Site 4</option>
    <option value="16">Site 5</option>
    <option value="32">Site 6</option>
</select>

Now I'd like to pre-select the options based on an integer value, e.g. the value 15 should pre-select Site 1, 2, 3 and 4.

As far as I know this can be done using the jQuery trigger method -

$('#uploadSitesDecoded').val([1,2,4,8]).trigger('change');

So what I'm trying to do is to convert 15 to a string or array as 1,2,4,8 (unless someone knows an easier way).

4 Answers

parseInt(n, 10).toString(2)

This will give you the bit by bit representation of n, you can then loop through it char by char to get the power of 2 values corresponding:

let n = 15; // The number you want to turn into an array of power of 2
let array = [];
let binaryRepresentation = parseInt(n, 10).toString(2);
binaryRepresentation = binaryRepresentation.split("").reverse().join(""); // You need to reverse the string to get the power of 2 corresponding
for(let i = binaryRepresentation.length - 1; i >= 0; i--){
     if(binaryRepresentation[i] == 1){
         array.push(Math.pow(2, i));
     }
}
console.log(array); // Check the array

This exemple will give you [8, 4, 2, 1]

One possible way to achieve this is to convert the integer value in to a binary string using toString(2). Then you can loop through the string and set the option matching the index of the string to selected, if the value is a 1. Something like this:

$('input').on('input', function() {
  var $options = $('#uploadSitesDecoded option');
  var binaryString = parseInt(this.value, 10).toString(2);
  binaryString.split('').reverse().forEach(function(n, i) {
    $options.eq(i).prop('selected', n === '1');
  });
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" value="1" min="0" max="63" /><br />
<select multiple class="form-control" name="uploadSites[]" id="uploadSitesDecoded" size="8">
  <option value="1">Site 1</option>
  <option value="2">Site 2</option>
  <option value="4">Site 3</option>
  <option value="8">Site 4</option>
  <option value="16">Site 5</option>
  <option value="32">Site 6</option>
</select>

I don't know if it is the most optimal way, but here is my solution. First I change the given int to a binary and than reverse it. Than loop over it to find the 1's in the binary.

function dec2bin(dec){
    return (dec >>> 0).toString(2);
}

function reverseString(str) {
    return str.split("").reverse().join("");
}

$(document).ready(function() {
  var binary = reverseString(dec2bin(15));
  var values = [];
  var step = 1;
  
  for (var i = 0; i < binary.length; i++) {
    if(parseInt(binary.charAt(i)) === 1){
      values.push(step);
    }
    step *=2;
  }
  
  $('#uploadSitesDecoded').val(values).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select multiple class="form-control" name="uploadSites[]" id="uploadSitesDecoded">
    <option value="1">Site 1</option>
    <option value="2">Site 2</option>
    <option value="4">Site 3</option>
    <option value="8">Site 4</option>
    <option value="16">Site 5</option>
    <option value="32">Site 6</option>
</select>

Related