Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Buffer read bits from Bytes

Tags:

node.js

binary

I have the following example buffers and trying to extract some data from this.

<Buffer 38 31 aa 5e>
<Buffer 1c b2 4e 5f>
<Buffer c4 c0 28 60>
<Buffer 04 7a 52 60>
<Buffer 14 17 cd 60>

The data is in the format

Byte 1 - UTC nanosecond LS byte

Byte 2 - UTC nanosecond

Byte 3 - UTC nanosecond

Byte 4 - bits 0-5 UTC nanosecond upper 6 bits, 6-7 raw bits for debugging

I get bit shifting when I need whole bytes together but never needed to concatenate this with bits of a byte too. Any help?

like image 478
Lee Armstrong Avatar asked Jul 07 '14 17:07

Lee Armstrong


People also ask

How do I decode buffer data in node JS?

In Node. js, the Buffer. toString() method is used to decode or convert a buffer to a string, according to the specified character encoding type. Converting a buffer to a string is known as encoding, and converting a string to a buffer is known as decoding.

What does the BUF toJSON () method return in node JS?

The toJSON() method returns a JSON object based on the Buffer object.

How does Nodejs buffer work?

The Buffer class in Node. js is designed to handle raw binary data. Each buffer corresponds to some raw memory allocated outside V8. Buffers act somewhat like arrays of integers, but aren't resizable and have a whole bunch of methods specifically for binary data.


2 Answers

You should be able to read the values as a single int and then use bitwise math to pull out the values.

// Read the value as little-endian since the least significant bytes are first.
var val = buf.readUInt32LE(0);

// Mask the last 2 bits out of the 32-bit value.
var nanoseconds = val & 0x3FFFFFFF;

// Mark just the final bits and convert to a boolean.
var bit6Set = !!(val & 0x40000000);
var bit7Set = !!(val & 0x80000000);
like image 119
loganfsmyth Avatar answered Sep 18 '22 15:09

loganfsmyth


I have seen a better solution so I would like to share:

_getNode(bitIndex: number, id: Buffer) {
  const byte   = ~~(bitIndex / 8); // which byte to look at
  const bit    = bitIndex % 8;     // which bit within the byte to look at
  const idByte = id[byte];         // grab the byte from the buffer
  if (idByte & Math.pow(2, (7 - bit))) { do something here } // check that the bit is set
}

It's just a little clearer / more concise. Notice how we use natural log2 pattern to our advantage to check if the bit is set.

like image 20
Craig O'Connor Avatar answered Sep 19 '22 15:09

Craig O'Connor