半精度浮点是指用16bit表示一个浮点数,最高1bit为符号位,中间5bit为指数a,低10bit为尾数bhtml
Value = (符号位)(1+b/1024)*(2^(a-16))python
程序很简单,用pyinstaller -F getExp.py压缩成getExp.exe(见另外一篇博客py文件打包成exe)能够用app
因为只取指数位,程序简单处理了符号位和尾数位htm
#coding = utf-8 if __name__ == '__main__': file = input('输入半精度浮点文件:\n') outfile = input('输出文件:\n') inputdata = [] with open(file, 'r') as f: for line in f.readlines(): item = line[2:] #这里假设输入数据是带有0x的16进制数如0x412F,因此要从0x后开始取 data = hex(eval(line)) #获取16进制数 dataout = bin(int(data, 16)) #转为二进制数 temp = int(dataout[2:], 2) #转为的二进制数是0b..须要从第三位开始取,而后将二进制转为十进制 exp = temp >> 10 #取十进制数的前6bit if exp > 31: #若是符号位是1的话 inputdata.append(exp-32) else: #符号位为0 inputdata.append(exp) with open(outfile, 'w+') as f_w: for item in inputdata: f_w.write(str(item)+'\n') print('Sucessfully!') input('Press any key to Exit:\n')