Lee Armstrong
Lee Armstrong

Reputation: 11450

NodeJS Buffer read bits from Bytes

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?

Upvotes: 8

Views: 12964

Answers (2)

Craig O&#39;Connor
Craig O&#39;Connor

Reputation: 163

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.

Upvotes: 2

loganfsmyth
loganfsmyth

Reputation: 161617

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);

Upvotes: 10

Related Questions