Node.js中二进制日志反向读取后的字节反转与交换问题排查
背景
我有一个二进制日志文件,每条日志占7字节:
- 前4字节为时间戳(用
writeUInt32BE写入) - 接下来1字节为标识位(用
writeUInt8写入数值1或2) - 最后2字节为4位数字(用
writeUInt16BE写入)
写入、正向读取并解码这些数据的流程均正常工作。由于日志是追加写入文件,最新日志位于文件末尾。为了获取最新日志并避免从头读取所有历史日志,我实现并测试了一个反向流。
问题
我无法将反向读取的数据解码为正确格式。我的处理步骤:
- 以反向流的方式读取日志
- 交换字节以恢复原始格式
代码如下:
// 此处为步长为+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
相关产品推荐
相关产品推荐

