Python结构解包与负数

2024-04-24 17:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

事实证明,无论是谁制造的硬件都没有2的补码表示法,为了表示负数,他们只需翻转MSB。在

struct是否有解码这些数字的方法?还是我得自己动手?在


Tags: 方法硬件符号数字解码链路struct表示法
1条回答
网友
1楼 · 发布于 2024-04-24 17:24:16

正如我在评论中所说,文件没有提到这种可能性。但是,如果你想用手来做转换,这并不难。下面是一个如何使用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))

这个例子的输出是:

^{pr2}$

希望这有帮助。在

相关问题 更多 >