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 ith bit using the bitmask 1 << i.  If the ith bit is set then bit becomes 1, otherwise it will be 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With