5

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);
};
1
  • I found this article extremely helpful with understanding how this stuff works.
    – CatDadCode
    Sep 21, 2020 at 23:07

1 Answer 1

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.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.

3
  • thanks, i just copy one octet, and use you code tmpByte = tmpSlice.toString('ascii', 0, 1).charCodeAt(0); var octet = tmpByte; Aug 6, 2013 at 20:00
  • 1
    another alternative without the ternary operator is: for (var i = 0; i < 8; i++) { var bit = octet >> 7 - i & 1; ... }
    – jJ'
    Aug 7, 2013 at 20:58
  • Good suggestion, I'm sure that is more efficient. Aug 7, 2013 at 21:04

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.