处理二进制
Uint8List data;
#偏移截取
ByteData headerData = ByteData.sublistView(data, 0, 12);
var header = headerData.buffer.asUint8List();
// 创建一个从输入二进制数据的
io.Readervar dataBuff = ByteData.view(header.buffer);
//从0开始读取四个字节
var msgid = dataBuff.getUint32(0, Endian.little)
//从4开始读取四个字节
var len = dataBuff.getUint32(4, Endian.little)
//转为utf8 文字
const decoder = Utf8Decoder();
var result = decoder.convert(
data, 12 , 12 + len);
Logger.log(result);
//utf8 文字 转 Uint8List
String str = "Hello, world!";
Uint8List uint8List = utf8.encode(str);
print(uint8List);
//使用字节偏移量(0、4、8)来设置每个字符的值 Uint32 需要4个字节
//使用字节偏移量(0、2、4)来设置每个字符的值,因为Int16需要2个字节
//Uint8 需要一个字节
static Uint8List packMsg(Msg msg) {
// 创建一个存放 bytes 字节的缓冲
var dataBuff = ByteData(0);
// 写 msgID
dataBuff.setUint32(0, msg.getMsgId(), Endian.little);
// 写 headerLen
dataBuff.setUint32(4, msg.getHeaderLen(), Endian.little);
// 写 bodyLen
dataBuff.setUint32(8, msg.getBodyLen(), Endian.little);
// 写 header
var header = msg.getHeader();
for (var i = 0; i < header.length; i++) {
dataBuff.setUint8(8 + i, header[i]);
}
// 写 data 数据
var body = msg.getBody();
for (var i = 0; i < body.length; i++) {
dataBuff.setUint8(8 + header.length + i, body[i]);
}
return dataBuff.buffer.asUint8List();
}
List<int> Uint8List 互转
List<int> intList = [1, 2, 3];
Uint8List uint8List = Uint8List.fromList(intList);
print(uint8List); // 输出: [1, 2, 3]
// 将Uint8List转换为List<int>
Uint8List uint8List2 = Uint8List.fromList([4, 5, 6]);
List<int> intList2 = uint8List2.toList();