简体   繁体   中英

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.

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:

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/

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 . If the i th bit is set then bit becomes 1 , otherwise it will be 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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