Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
};
like image 667
Kolomnitcki Avatar asked Aug 06 '13 19:08

Kolomnitcki


1 Answers

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

like image 117
Andrew Clark Avatar answered Oct 23 '22 10:10

Andrew Clark