8

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?

2 Answers 2

10

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Oh neat, how do I get the raw bit values of the last two bits though? Also I don't get the "& 0x3FFFFFFF" what operation does that perform?
It appears the last 2 bits are possibly not correct? I think I need the raw values here?
@LeeArmstrong Updated the method to grab individual bits and added a link that will help explain the bitwise math I am doing.
Thanks, the link helps a lot!
2

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.

1 Comment

Just notice that operating on the buffer directly completely ignores endianness. This only works if you know all of your buffers are of the correct endianness.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.