如何将(二进制)整数转换为数组?

sec*_*ave 4 javascript arrays binary jquery

我的HTML代码中有以下表单选择字段 -

<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>
Run Code Online (Sandbox Code Playgroud)

现在我想基于整数值预先选择选项,例如,值15应该预先选择站点1,2,3和4.

据我所知,这可以使用jQuery触发器方法完成 -

$('#uploadSitesDecoded').val([1,2,4,8]).trigger('change');
Run Code Online (Sandbox Code Playgroud)

所以我要做的是将15转换为字符串或数组为1,2,4,8(除非有人知道更简单的方法).

R.D*_*eil 6

parseInt(n, 10).toString(2)

这将为您提供n的逐位表示,然后您可以通过char循环遍历char以获得2个值对应的幂:

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
Run Code Online (Sandbox Code Playgroud)

这个例子会给你 [8, 4, 2, 1]

  • 谢谢!几乎我在寻找,但看起来像6将返回[2,1] (3认同)