gpt4 book ai didi

Python 结构解包和负数

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:06 25 4
gpt4 key购买 nike

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

事实证明,制造硬件的人并不关心 2 的补码表示法,而要表示负数,他们只是翻转 MSB。

struct有办法解码这些数字吗?或者我必须自己进行位操作?

最佳答案

正如我在评论中所说,文档没有提到这种可能性。不过,如果你想手动进行转换,也不是太困难。这是一个如何使用 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]

希望这有帮助。

关于Python 结构解包和负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45101312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com