Harshal Bora
Harshal Bora

Reputation: 11

How to convert 16bit hexadecimal and binary representations to decimal float (and vice versa) in python?

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]

Basically what I want is:

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

Answers (1)

Harshal Bora
Harshal Bora

Reputation: 11

So, I found the solution after a bit of research and I'm posting it here for anyone who might need the same.

import struct
import numpy as np
bin = "0010100011110101"
hex = "28f5"
dec_float = 0.03872680

FP16 binary to decimal float

y = struct.pack("H",int(bin,2))
float = np.frombuffer(y, dtype =np.float16)[0]

FP16 hex to decimal float

y = struct.pack("H",int(hex,16))
float = np.frombuffer(y, dtype =np.float16)[0]

Decimal float to FP16 binary

binary = struct.unpack('H',struct.pack('e',dec_float))[0]
binary = bin(binary)
binary = binary[2:]
binary = "0"*2 + binary

Decimal float to FP16 hex

hexa = struct.unpack('H',struct.pack('e',dec_float))[0]
hexa = hex(hexa)
hexa = hexa[2:]

Upvotes: 0

Related Questions