NodeJS缓冲区从字节读取位

Lee*_*ong 4 binary node.js

我有以下示例缓冲区并尝试从中提取一些数据.

<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>
Run Code Online (Sandbox Code Playgroud)

数据采用格式

字节1 - UTC纳秒LS字节

字节2 - UTC纳秒

字节3 - UTC纳秒

字节4 - 位0-5 UTC纳秒高6位,6-7个原始位用于调试

当我需要整个字节时,我得到了一些位移,但是从来不需要将它与一个字节的位连接起来.有帮助吗?

log*_*yth 6

您应该能够将值作为单个int读取,然后使用按位数学来提取值.

// 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);
Run Code Online (Sandbox Code Playgroud)