拉取与位掩码关联的数组值

Pull array values associated with bitmask

我有一个简单的位掩码,3"011" in base 2)表示我应该提取 array[0]array[1] 而不是 array[2]

执行此操作的有效方法是什么?

最终,我生成了一个新数组,其值通过了 .filter

像这样:

var bitmask = 37, // "100101"
    array = ["a", "b", "c", "d", "e", "f"];

var array2 = array.filter((value, index) => {
    // do something with bitmask and index to return true
});

// array2 should be ["a", "c", "f"];

var bitmask = 5, idx=0;
// Loop till bitmask reach 0, works when bitmask >= 0
// If you want to sure instead of implicit type converting (from number to boolean)
// Just change it to while(bitmask >= 0)
while(bitmask){
   // If the rightmost bit is 1, take the array[index]
   if(bitmask & 1) console.log("take arr["+idx+"]");
   // Shift right by 1 bit, say 5 = 101,  this will make the number become 2 = 10
   bitmask>>=1; 
   // Increase the index 
   idx++;
}

使用您自己的示例,以下代码有效:

var bitmask = 37, // "100101"
    array = ["a", "b", "c", "d", "e", "f"],
    idx = 0;
var array2 = [];
while(bitmask){
   if(bitmask & 1) array2.push(array[idx]);
   bitmask>>=1; 
   idx++;
}

简单的用一些位操作循环一下。因为它一点一点地循环,我认为这是最快的

一种方法是将您的数字转换为二进制字符串,然后检查过滤器中位掩码的索引是否为 "1"

    var bitmask = (37).toString(2), // "100101"
        array = ["a", "b", "c", "d", "e", "f"];
    
    var array2 = array.filter((value, index) => {
        if(bitmask[index] == "1") return value;
    });
    
    console.log(array2);

扩展您的原始示例,您可以这样做:

var bitmask = 37, // "100101"
    array = ["a", "b", "c", "d", "e", "f"];

var array2 = array.filter((value, index) => {
    // do something with bitmask and index to return true
    return bitmask & (1 << index);
});

// array2 should be ["a", "c", "f"];
console.log(array2);