bodokaiser
bodokaiser

Reputation: 15752

Nodejs Buffer: How to read out bit flags?

I am listening on data events on a tcp socket.

Each data event provides me a buffer which is a frame of a protocol. The first byte works as header and contains some bit flags I would like to access.

Until there listening on data events and getting the first byte looks as:

socket.on('data', function(buff) {
    console.log(buff[0]); // returns 129
});

If I now want to check the first bit then I must transform the 129 to bit format and then check out the first number.

129 => 1000 0001
       |

As we know JavaScript does not support binaries.

I am now wondering if the node buffer object allows me to work bit wise and if yes how this would look like?

Regards

Upvotes: 1

Views: 4053

Answers (1)

pimvdb
pimvdb

Reputation: 154948

Checking a flag can be done using the & operator.

For a flag that does contain the first bit:

1000 0001      129
1000 0000      128
--------- &
1000 0000      128

For a flag that doesn't contain the first bit:

0101 0001      81
1000 0000      128
--------- &
0000 0000      0

So the result is either the flag (if the flag has been set) or zero (if the flag has not been set). Hence, you could create a function (where flag is a power of 2):

var containsFlag = function(number, flag) {
  return (number & flag) === flag;
};

containsFlag(129, 128);  // true
containsFlag(81, 128);   // false

Upvotes: 4

Related Questions