是否与[] .pop()有点相同?

时间:2014-01-22 06:29:56

标签: javascript bit-manipulation

我需要迭代一个位图,从最小的位开始。

在第一个循环中,我需要检查最小位,然后检查第二个最小位。因此,如果我的值为6,则会获得false, true, true

我想编写如下代码:

if (bitmap.pop()){

但那不是一种选择。什么是优雅的替代品?

4 个答案:

答案 0 :(得分:1)

有效地:使用bit twiddling.

效率较低:将数字的二进制表示的0和1放入数组中,然后使用Array.pop()as @zerkms suggests

答案 1 :(得分:1)

使用按位运算符,这应该可以工作:

var a = 6;

do {
    if (a & 1) {
        // true
    } else {
        // false
    }
} while (a = a >> 1);

如果您不想使用经典方法并且需要类似pop()的函数,您可以使用定义pop()函数的原型对象,如下所示:

function PopNumbers (startNumber) {
    this.startNumber = startNumber;
}

PopNumbers.prototype.hasNext = function () {
    return (this.nextNumber === undefined || this.nextNumber !== 0);
};

PopNumbers.prototype.pop = function () {
    if (this.hasNext()) {
            var currentNumber = this.nextNumber || this.startNumber;
            this.nextNumber = currentNumber >> 1;
            return !!(currentNumber & 1);
    }
};

小提琴:http://jsfiddle.net/pascalockert/JHM2f/

答案 2 :(得分:0)

“优雅”的标准是什么?也许:

function flipBits(x) {
  var arr = [];
  do {
    arr.push(!!(x % 2));
  } while (x = x >> 1)
  return arr;
}

alert(flipBits(6)) // false, true, true
alert(flipBits(7)) // true, true, true
alert(flipBits(7)) // true, true, false, true, true

答案 3 :(得分:0)

您可以使用简单的&1操作来提取最后一位。现在,要移动位,您只需在最后一项上使用>>运算符即可。为了避免必须在所有条目中移位值,我们可以简单地跟踪最后一个整数中剩余的位数。

这是一个假设您在位数组的最后一个整数中具有最低有效位并且每个条目使用32位的示例。

var values = [0xffffffff, 0xffffffff, 0xffffff01];

var lsbSize = 32;

function pop() {
    var value = values[values.length-1] & 1; // extract last bit
    value = value?true:false;
    values[values.length-1] = values[values.length-1] >> 1; // shift out the last bit in the last entry
    lsbSize--;
    if(lsbSize == 0) { // if there are no more bits left in the last entry. simply pop it out and reset the size
        values.pop();
        lsbSize = 32;
    }
    return value;
}

这是jsFiddle example

相关问题