如何将按位的值组合成int数组

How to scompose bitwise value into int array?

本文关键字:组合 int 数组      更新时间:2023-09-26

假设我有一个按位值66,它由2和64组成。是否有一种方法在javascript中按位组合,以便结果将是整数数组[2,64]?

//Example 
function transformBW(x) {   //where x = 82;
    ---------
    var result = [2,16,64];  //desired result
    return result;
};
// transformBW(66) = [2,64];

欢迎任何帮助。

谢谢

// Assumes n is an integer >= 0
function transformBW( n ) {
    var r = [];
    var bv = 1;
    while ( n >= 1 ) {
        if ( n % 2 == 1 ) {
            // Add the bit value (bv) of the LSB left in n
            r.push( bv );
            // Clear that bit
            n -= 1;
        }
        // Shift n down 1 bit, adjusting bit value to the new LSB's value
        bv += bv;
        n /= 2;
    }
    return r;
}