【问题标题】:How to scompose bitwise value into int array?如何将按位值组合成 int 数组?
【发布时间】:2015-09-01 13:33:13
【问题描述】:
假设 i 的位值为 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];
欢迎任何帮助。
谢谢
【问题讨论】:
标签:
javascript
arrays
int
bit-manipulation
divide
【解决方案1】:
// 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;
}