I’m trying to write a basic FP16 based calculator in python to help me debug some hardware. Can’t seem to find how to convert 16b hex values unto floating point values I can use in my code to do the math. I see lots of online references to numpy but I think the float16 constructor expects a string like float16(“1.2345”). I guess what I’m looking for is something like float16(“0xabcd”).
Thanks!
Advertisement
Answer
The numpy.float16
is indeed a signed floating point format with a 5-bit exponent and 10-bit mantissa.
To get the result of your example:
JavaScript
x
4
1
import numpy as np
2
3
np.frombuffer(b'xabxcd', dtype=np.float16, count=1)
4
Result:
JavaScript
1
2
1
array([-22.67], dtype=float16)
2
Or, to show how you can encode and decode the other example 1.2345
:
JavaScript
1
8
1
import numpy as np
2
3
a = np.array([1.2345], numpy.float16)
4
b = a.tobytes()
5
print(b)
6
c = np.frombuffer(b, dtype=np.float16, count=1)
7
print(c)
8
Result:
JavaScript
1
3
1
b'xf0<'
2
[1.234]
3
If you literally needed to turn the string you provided into an FP16:
JavaScript
1
8
1
import numpy as np
2
3
s = "0xabcd"
4
b = int("0xabcd", base=16).to_bytes(2, 'big')
5
print(b)
6
c = np.frombuffer(b, dtype=np.float16, count=1)
7
print(c)
8
Output:
JavaScript
1
3
1
b'xabxcd'
2
[-22.67]
3