Python struct unpack和负数

时间:2017-07-14 10:59:33

标签: python python-3.x struct binary

我正在使用struct.unpack('>h', ...)解压缩一些我通过串行链接从某些硬件接收的16位有符号数字。

事实证明,无论谁制造硬件都没有2的补码表示,并且代表负数,他们只是翻转MSB。

struct是否有解码这些数字的方法?或者我自己必须做一些操作?

2 个答案:

答案 0 :(得分: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]

希望这有帮助。

答案 1 :(得分:0)

这对我有用: hexstring = "c2280000" #应该是-42

print(struct.unpack(">f", struct.pack('>L', int("0x"+hexstring, 16)))[0])

从 Masahif 找到的答案: https://gist.github.com/masahif/418953