如何将按位值组合成 int 数组?
How to scompose bitwise value into int array?
假设我的位值为 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;
}
假设我的位值为 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;
}