2017-07-14 57 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] 

希望这有助于。