简体   繁体   English

node.js - 将一个字节切成位

[英]node.js - Slice a byte into bits

How can I take an octet from the buffer and turn it into a binary sequence? 如何从缓冲区中取一个八位字节并将其转换为二进制序列? I want to decode protocol rfc1035 through node.js but find it difficult to work with bits. 我想通过node.js解码协议rfc1035 ,但发现很难处理位。

Here is a code, but it does not suit me - because it is a blackbox for me: 这是一个代码,但它不适合我 - 因为它对我来说是一个黑盒子:

var sliceBits = function(b, off, len) {
  var s = 7 - (off + len - 1);

  b = b >>> s;
  return b & ~(0xff << len);
};

Use a bitmask , an octet is 8 bits so you can do something like the following: 使用位掩码 ,八位位组是8位,因此您可以执行以下操作:

for (var i = 7; i >= 0; i--) {
   var bit = octet & (1 << i) ? 1 : 0;
   // do something with the bit (push to an array if you want a sequence)
}

Example: http://jsfiddle.net/3NUVq/ 示例: http//jsfiddle.net/3NUVq/

You could probably make this more efficient, but the approach is pretty straightforward. 你可能会提高效率,但这种方法非常简单。 This loops over an offset i , from 7 down to 0, and finds the i th bit using the bitmask 1 << i . 这循环在偏移i ,从7下降到0,并使用位掩码1 << i找到第i位。 If the i th bit is set then bit becomes 1 , otherwise it will be 0 . 如果第i位置位则bit变为1 ,否则为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM