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?
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.
The toJSON() method returns a JSON object based on the Buffer object.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With