Reputation: 11
I am working on a problem which requires me to convert hexadecimal and binary FP16 representation of float numbers to decimal float. I also need to convert decimal float numbers to FP16 hexadecimal and binary representations.
There are a lot of solutions for conversion of FP32 numbers. But I specifically require FP16 representations.
I already found a solution for FP16 binary to decimal float:
a = struct.pack("H",int("0010100011110101",2))
float = np.frombuffer(a, dtype =np.float16)[0]
FP16 binary -> decimal float (0010100011110101 -> 0.0387268066)
FP16 hex -> decimal float (28f5 -> 0.0387268066)
decimal float -> FP16 binary (0.0387268066 -> 0010100011110101)
decimal float -> FP16 hex (0.0387268066 -> 28f5)
Upvotes: 1
Views: 2986
Reputation: 11
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:]
Upvotes: 0