2024-04-24 17:24:16 发布
网友
我使用struct.unpack('>h', ...)来解压一些16位有符号的数字,这些数字是通过串行链路从某个硬件接收的。在
struct.unpack('>h', ...)
事实证明,无论是谁制造的硬件都没有2的补码表示法,为了表示负数,他们只需翻转MSB。在
struct是否有解码这些数字的方法?还是我得自己动手?在
struct
正如我在评论中所说,文件没有提到这种可能性。但是,如果你想用手来做转换,这并不难。下面是一个如何使用numpy数组的简短示例:
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))
这个例子的输出是:
希望这有帮助。在
正如我在评论中所说,文件没有提到这种可能性。但是,如果你想用手来做转换,这并不难。下面是一个如何使用
numpy
数组的简短示例:这个例子的输出是:
^{pr2}$希望这有帮助。在
相关问题 更多 >
编程相关推荐