flutter中的字节数据解析

Byte data Parsing in flutter

嗨,我需要解析来自 api 的响应的字节数据,数据是

[0, 2, 0, 44, 0, 6, 58, 1, 0, 1, 109, 85, 0, 0, 0, 1, 0, 1, 111, 97, 0, 115, 224, 4, 0, 0, 0, 0, 0, 0, 1, 114, 0, 1, 115, 169, 0, 1, 116, 18, 0, 1, 108, 121, 0, 1, 113, 241, 0, 44, 0, 13, 128, 1, 0, 0, 55, 200, 0, 0, 0, 10, 0, 0, 55, 227, 5, 172, 149, 3, 0, 0, 84, 154, 0, 0, 0, 0, 0, 0, 56, 79, 0, 0, 57, 28, 0, 0, 54, 226, 0, 0, 56, 89]

根据api提供者解析数据有一定的规则如下

A 前两个字节([0 - 2] -- SHORT 或 int16)表示消息中的数据包数。

B 接下来的两个字节([2 - 4] -- SHORT 或 int16)表示第一个数据包的长度(字节数)。

C 下一个字节系列 ([4 - 4+B]) 是报价包。

D 接下来的两个字节([4+B - 4+B+2] -- SHORT or int16)表示第二个数据包的长度(字节数)。

C 下一个字节系列 ([4+B+2 - 4+B+2+D]) 是下一个报价包。

请有人帮助我如何根据 dart 中的这些规则解析这些数据。我卡住了谢谢你的帮助

首先,您需要将整数列表转换为字节列表:

final byteList = Uint8List.fromList(responseList);

然后您需要从该字节列表创建一个 ByteData

final byteData = ByteData.view(byteList.buffer);

然后您可以在各种字节偏移处解析您想要的各种字节、短整型、整数或长整型。例如:

final packetNum = byteData.getUint16(0);

final firstPacketLength = byteData.getUint16(2);
final firstPacketView = ByteData.sublistView(byteData, 4, 4 + firstPacketLength);
// Do whatever you need for that packet

final secondPacketPos = 4 + firstPacketLength;
final secondPacketLength = byteData.getUint16(secondPacketPos),
final secondPacketView = ByteData.sublistView(byteData, secondPacketPos + 2, 4 + secondPacketLength);
// Do whatever you need for the saecond packet