在Buffer Nodejs中写入位

时间:2018-05-07 12:19:17

标签: node.js byte buffer bit

朋友怎么能把一点写入Node js Buffer,我可以写Byte,整数等但不知道如何写位。可能吗?如果是的话怎么样? 我应该在缓冲区1或0中写一个bollean并使用readBit()在API中读取它,这就是为什么我需要在缓冲区中写一点。

1 个答案:

答案 0 :(得分:3)

你不能直接访问一个位,但可以简单地在JS中做一些魔术。

这将使您能够读取和写入节点缓冲区(Uint8Array)的单个位。

var buffer = new Uint8Array(1);

function readBit(buffer, i, bit){
  return (buffer[i] >> bit) % 2;
}

function setBit(buffer, i, bit, value){
  if(value == 0){
    buffer[i] &= ~(1 << bit);
  }else{
    buffer[i] |= (1 << bit);
  }
}

// write bit 0 of buffer[0]
setBit(buffer, 0, 0, 1)

// write bit 1 of buffer[0]
setBit(buffer, 0, 1, 1)
setBit(buffer, 0, 1, 0)

// write bit 2 of buffer[0]
setBit(buffer, 0, 2, 0)

// write bit 3 of buffer[0]
setBit(buffer, 0, 3, 0)
setBit(buffer, 0, 3, 1)

// read back the bits
console.log(
  readBit(buffer, 0, 0),
  readBit(buffer, 0, 1),
  readBit(buffer, 0, 2),
  readBit(buffer, 0, 3)
);