2017-12-02 186 views
0

我有一个通过TCP发送的'double'(来自MATLAB)的数组。将发送的TCP数据转换为python中的可打印文本

接收端(PYTHON)中,当作为字符串印刷,被示出为:

> b'?\xf0\x00\x00\x00\x00\x00\[email protected][\xc0\x00\x00\x00\x00\[email protected]`\x00\x00\x00\x00\[email protected]\x00\x00\x00\x00\[email protected]\xb0\x00\x00\x00\x00\[email protected]\x7f\xf0\x00\x00\x00\x00\[email protected]\x83\x18\x00\x00\x00\x00\[email protected]\x868\x00\x00\x00\x00\[email protected]\x87\xe0\x00\x00\x00\x00\[email protected][\x80\x00\x00\x00\x00\[email protected]@\x00\x00\x00\x00\[email protected]`\x00\x00\x00\x00\[email protected]\xa0\x00\x00\x00\x00\[email protected]\x7f\xe0\x00\x00\x00\x00\[email protected]\x83\x10\x00\x00\x00\x00\[email protected]\x860\x00\x00\x00\x00\[email protected]\x87\xd8\x00\x00\x00\x00\[email protected]\x88\x90\x00\x00\x00\x00\x00' 

如何解码此看起来相同,作为初始是可读的?

回答

1

使用标准库中的struct模块来解压二进制数据。

struct.unpack函数接受两个参数,格式字符串定义二进制数据的布局和数据本身。

由于数据来自网络,我们假设网络订单(格式为!);数据是加倍的数组,因此我们将使用双精度型(格式d)。 struct模块为double定义了8的大小,而bytestring的长度为144,所以这是18倍,给出格式字符串!18d

解压数据:

>>> unpacked = struct.unpack('!18d', data) 
>>> unpacked                                                  
(1.0,                                                  
111.0,                                                  
211.0,                                                  
311.0,                                                  
411.0,                                                  
511.0,                                                  
611.0,                                                  
711.0,                                                  
764.0,                                                  
110.0,                                                  
210.0,                                                  
310.0,                                                  
410.0, 
510.0, 
610.0, 
710.0, 
763.0, 
786.0) 
>>> 

如果这个输出是不是你可以有你期待什么,然后用一些结构模块中定义的其他格式进行实验,或者找出Matlab的串行化到底有数据通过网络传输。

相关问题