2017-07-14 84 views
1

我使用struct.unpack('>h', ...)來解壓一些16位有符號的數字,我通過串行鏈接從某些硬件上收到。Python結構解壓縮和負數

事實證明,製造硬件的人沒有2的補碼數字表示的心臟並且代表負數,他們只是翻轉MSB。

struct是否有解碼這些數字的方法?或者我必須自己做點位操作?

+0

看着文檔,我幾乎可以說這是你必須要做的事情... –

+0

如果你使用'> H''而不是''> h'',它不應該太難去做 ... –

回答

1

正如我在評論中所說的,文檔沒有提到這種可能性。但是,如果您想手動進行轉換,則不會太困難。這裏很短的例子,如何使用numpy數組做到這一點:

import numpy as np 

def hw2complement(numbers): 
    mask = 0x8000 
    return (
     ((mask&(~numbers))>>15)*(numbers&(~mask)) + 
     ((mask&numbers)>>15)*(~(numbers&(~mask))+1) 
    ) 


#some positive numbers 
positives = np.array([1, 7, 42, 83], dtype=np.uint16) 
print ('positives =', positives) 

#generating negative numbers with the technique of your hardware: 
mask = 0x8000 
hw_negatives = positives+mask 
print('hw_negatives =', hw_negatives) 

#converting both the positive and negative numbers to the 
#complement number representation 
print ('positives ->', hw2complement(positives)) 
print ('hw_negatives ->',hw2complement(hw_negatives)) 

這個例子的輸出是:

positives = [ 1 7 42 83] 
hw_negatives = [32769 32775 32810 32851] 
positives -> [ 1 7 42 83] 
hw_negatives -> [ -1 -7 -42 -83] 

希望這有助於。