半精度浮點是指用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')