【问题标题】:NodeJS Buffer read bits from BytesNodeJS 缓冲区从字节中读取位
【发布时间】:2017-08-15 06:13:54
【问题描述】:

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

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

数据的格式

字节 1 - UTC 纳秒 LS 字节

字节 2 - UTC 纳秒

字节 3 - UTC 纳秒

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

当我需要将整个字节放在一起但从来不需要将它与一个字节的位连接时,我会移位。有什么帮助吗?

【问题讨论】:

    标签: node.js binary


    【解决方案1】:

    您应该能够将值作为单个 int 读取,然后使用 bitwise math 提取值。

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

    【讨论】:

    • 哦,太好了,我如何获得最后两位的原始位值?另外我没有得到“& 0x3FFFFFFF”这执行了什么操作?
    • 看起来最后 2 位可能不正确?我想我需要这里的原始值?
    • @LeeArmstrong 更新了获取单个位的方法并添加了一个链接,以帮助解释我正在做的按位数学。
    • 谢谢,这个链接很有帮助!
    【解决方案2】:

    我看到了更好的解决方案,所以我想分享一下:

    _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
    }
    

    它只是更清晰/更简洁。请注意我们如何使用自然 log2 模式来检查该位是否已设置。

    【讨论】:

      猜你喜欢
      • 2015-07-26
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      相关资源
      最近更新 更多