You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中二进制日志反向读取后的字节反转与交换问题排查

背景

我有一个二进制日志文件,每条日志占7字节:

  • 前4字节为时间戳(用writeUInt32BE写入)
  • 接下来1字节为标识位(用writeUInt8写入数值1或2)
  • 最后2字节为4位数字(用writeUInt16BE写入)

写入、正向读取并解码这些数据的流程均正常工作。由于日志是追加写入文件,最新日志位于文件末尾。为了获取最新日志并避免从头读取所有历史日志,我实现并测试了一个反向流。

问题

我无法将反向读取的数据解码为正确格式。我的处理步骤:

  1. 以反向流的方式读取日志
  2. 交换字节以恢复原始格式

代码如下:

// 此处为步长为+7的for循环
const byte1 = chunk.readUInt8(i); // 4位数字的第一个字节
const byte2 = chunk.readUInt8(i + 1); // 4位数字的第二个字节
const indicator = chunk.readUInt8(i + 2); // 共1字节的标识位
const timestampBytes = [
      chunk.readUInt8(i + 3), // 字节3
      chunk.readUInt8(i + 4), // 字节4
      chunk.readUInt8(i + 5), // 字节5
      chunk.readUInt8(i + 6), // 字节6
];

const fourDigitNumber = (byte2 << 8) | byte1; // 交换字节

// 交换时间戳字节以生成正确的UInt32值
const timestamp =
      (timestampBytes[3] << 24) |
      (timestampBytes[2] << 16) |
      (timestampBytes[1] << 8) |
       timestampBytes[0];

我的字节交换操作是否正确?

我还尝试了反转字节,但仍然得到错误结果:

Buffer.from(chunk.slice(i, i + 7).reverse());
当前结果

4位数字和标识位的解析结果基本正确,但时间戳有时偏差极大(预期为2025年左右,却出现2027年、1979年等年份)。

内容的提问来源于stack exchange,提问作者user423896

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 22:15:56