如何在JavaScript中设置,清除和切换一个位?

时间:2009-09-17 02:31:00

标签: javascript numbers bit-manipulation

如何在JavaScript中设置,清除,切换和检查一下?

4 个答案:

答案 0 :(得分:158)

要掩饰一下:

var mask = 1 << 5; // gets the 6th bit

测试是否设置了一个位:

if ((n & mask) != 0) {
  // bit is set
} else {
  // bit is not set
}

设置位:

n |= mask;

要清楚一点:

n &= ~mask;

要切换一下:

n ^= mask;

请参阅Javascript bitwise operators

答案 1 :(得分:27)

我想添加一些东西(感谢@cletus)

function bit_test(num, bit){
    return ((num>>bit) % 2 != 0)
}

function bit_set(num, bit){
    return num | 1<<bit;
}

function bit_clear(num, bit){
    return num & ~(1<<bit);
}

function bit_toggle(num, bit){
    return bit_test(num, bit) ? bit_clear(num, bit) : bit_set(num, bit);
}

答案 2 :(得分:9)

获取位

function getBit(number, bitPosition) {
  return (number & (1 << bitPosition)) === 0 ? 0 : 1;
}

设置位

function setBit(number, bitPosition) {
  return number | (1 << bitPosition);
}

清除位

function clearBit(number, bitPosition) {
  const mask = ~(1 << bitPosition);
  return number & mask;
}

更新位

function updateBit(number, bitPosition, bitValue) {
  const bitValueNormalized = bitValue ? 1 : 0;
  const clearMask = ~(1 << bitPosition);
  return (number & clearMask) | (bitValueNormalized << bitPosition);
}

示例取自JavaScript Algorithms and Data Structures存储库。

答案 3 :(得分:3)

我在@cletus信息的帮助下构建了一个BitSet类:

function BitSet() {
    this.n = 0;
}

BitSet.prototype.set = function(p) {
    this.n |= (1 << p);
}

BitSet.prototype.test = function(p) {
    return (this.n & (1 << p)) !== 0;
}

BitSet.prototype.clear = function(p) {
    this.n &= ~(1 << p);
}

BitSet.prototype.toggle = function(p) {
    this.n ^= (1 << p);
}