python补码转源码

需求是这样的:
我用python从传感器一个字节一个字节的读取数据,传感器内部使用两个字节来表示一个数据单元(使用的补码表示整数),所以我需要用python将两个字节重新拼接起来让后将补码装换成python的源码(python使用原码表示整数):

import matplotlib.pyplot as plt
import matplotlib as mp
def byte16ToInt(byte16):
    if((byte16&0x8000)==0):
        r= byte16
    else:
        byte16=byte16^0xffff
        byte16=byte16+1
        r= -byte16
    return r
r=0x0001
x=[]
y=[]

#test
for i in range(0,65535):
    x.append(i);
    y.append(byte16ToInt(r))
    r+=1
    
mp.rcParams['font.family']='STFangsong'#修改了全局变量
plt.plot(x,y)
plt.xlabel("补码")
plt.ylabel("原码")
plt.title("python补码转原码")
figure.show()

测试输出图:

猜你喜欢

转载自www.cnblogs.com/sunhere/p/12930169.html
今日推荐