我正在解决一个问题,要求我将浮点数的十六进制和二进制FP16表示形式转换为十进制浮点数。我还需要将十进制浮点数转换为FP16十六进制和二进制表示形式。
FP32数字转换有很多解决方案。但是我特别需要FP16表示形式。
我已经找到了将FP16二进制转换为十进制浮点数的解决方案:
a = struct.pack("H",int("0010100011110101",2))
float = np.frombuffer(a, dtype =np.float16)[0]
FP16二进制->十进制浮点数(0010100011110101-> 0.0387268066)
FP16十六进制->十进制浮点数(28f5-> 0.0387268066)
十进制浮点数-> FP16二进制(0.0387268066-> 0010100011110101)
十进制浮点数-> FP16十六进制(0.0387268066-> 28f5)
import struct
import numpy as np
bin = "0010100011110101"
hex = "28f5"
dec_float = 0.03872680
y = struct.pack("H",int(bin,2))
float = np.frombuffer(y, dtype =np.float16)[0]
y = struct.pack("H",int(hex,16))
float = np.frombuffer(y, dtype =np.float16)[0]
binary = struct.unpack('H',struct.pack('e',dec_float))[0]
binary = bin(binary)
binary = binary[2:]
binary = "0"*2 + binary
hexa = struct.unpack('H',struct.pack('e',dec_float))[0]
hexa = hex(hexa)
hexa = hexa[2:]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句