2017-12-02 187 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的串行化到底有數據通過網絡傳輸。

相關問題