javascript - node.js - Slice a byte into bits - Stack Overflow

admin2025-03-19  4

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);
};

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);
};
Share Improve this question edited Aug 6, 2013 at 19:38 Sergey Weiss 5,9748 gold badges32 silver badges40 bronze badges asked Aug 6, 2013 at 19:15 KolomnitckiKolomnitcki 431 silver badge3 bronze badges 1
  • I found this article extremely helpful with understanding how this stuff works. – ChevCast Commented Sep 21, 2020 at 23:07
Add a ment  | 

1 Answer 1

Reset to default 7

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/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 ith bit using the bitmask 1 << i. If the ith bit is set then bit bees 1, otherwise it will be 0.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1742389111a211149.html

最新回复(0)