我正在使用套接字,结构用于通过 tcp/ip 协议接收和解包接收到的字节消息,我得到的元组包含数字数据以及按照合同定义的顺序的字节。示例数据如下...
示例:从 tcp ip 接收缓冲区数据
buffer = sock.recv(61)
将字节解压缩为预定义的结构格式
tup_data = struct.unpack("<lll8s17sh22s", buffer)
tup_data
(61,12000,4000,b'msg\x00\x00\x00\x00\x00',b'anther
msg\x00\x00\x00\x00\x00\x00\x00',4,b'yet another
msg\x00\x00\x00\x00\x00\x00\x00')
因为数据是高度流式传输的并且执行时间很重要......我不想通过使用任何循环和 isinstance() 方法来加载 cpu。由于定义了字节的位置,所以我目前使用 as
processed_data = (*tup_data[:3],
tup_data[3].strip(b"\x00").decode(),
tup_data[4].strip(b"\x00").decode(),
tup_data[5],
tup_data[6].strip(b"\x00").decode())
processed_data
(61,12000,4000,"msg","anther msg",4,"yet another msg")
有没有什么神奇的方法可以一次性将字节转换为所需的字符串,因为字节的位置是已知的......??