hex2fp.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import pandas as pd
  2. import math
  3. def dec_mantissa(bin_mantissa):
  4. res = 0
  5. for k in range(len(bin_mantissa)):
  6. res = res + (int(bin_mantissa[k]) * (2 ** (-1 - k)))
  7. return res
  8. def hex2dec(hex):
  9. binary = "{0:08b}".format(int(hex, 16))
  10. if len(binary) < 16:
  11. while len(binary) < 16:
  12. binary = "0" + binary
  13. sign = 1
  14. else:
  15. sign = -1 ** int(binary[0])
  16. exp = 2 ** (int(binary[1:6], 2) - 16)
  17. mantissa = 1 + dec_mantissa(binary[6:])
  18. return [binary, sign * exp * mantissa]
  19. # df = pd.read_csv("fp16_test.hex")
  20. # bins = []
  21. # decs = []
  22. # for i in range(df.shape[0]):
  23. # hexs = df.iloc[i][0].split()
  24. # bins.append([])
  25. # decs.append([])
  26. # for j in range(4):
  27. # bins[i].append("{0:08b}".format(int(hexs[j], 16)))
  28. # exp = 2 ** (int(bins[i][j][1:6], 2) - 16)
  29. # sign = -1 ** int(bins[i][j][0])
  30. # mantissa = 1 + dec_mantissa(bins[i][j][6:])
  31. # decs[i].append(sign * exp * mantissa)
  32. input_1 = "bbeb"
  33. input_2 = "58fe"
  34. result = "d8f1"
  35. calc_res = "d9f1"
  36. print("input 1 :", input_1, ", ", hex2dec(input_1)[0], ", ", hex2dec(input_1)[1])
  37. print("input 2 :", input_2, ", ", hex2dec(input_2)[0], ", ", hex2dec(input_2)[1])
  38. print("result :", result, ", ", hex2dec(result)[0], ", ", hex2dec(result)[1])
  39. print("calc res:", calc_res, ", ", hex2dec(calc_res)[0], ", ", hex2dec(calc_res)[1])