1

我正在使用套接字,结构用于通过 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")

有没有什么神奇的方法可以一次性将字节转换为所需的字符串,因为字节的位置是已知的......??

4

1 回答 1

0

由于您struct.unpack用于解压缓冲区并且由于format-characters图表的原因,您无法将字符串格式作为输出。因此,您应该\x00在源中去除额外的内容,或者只使用生成器理解如下来重新格式化作为字节实例的项目。

In [12]: tuple(i.strip(b'\x00').decode() if isinstance(i, bytes) else i for i in t)
Out[12]: (61, 12000, 4000, 'msg', 'anther msg', 4, 'yet another msg')
于 2018-06-02T09:51:19.760 回答