简体   繁体   中英

Convert 16 bit hex value to FP16 in Python?

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!

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:

import numpy as np

np.frombuffer(b'\xab\xcd', dtype=np.float16, count=1)

Result:

array([-22.67], dtype=float16)

Or, to show how you can encode and decode the other example 1.2345 :

import numpy as np

a = np.array([1.2345], numpy.float16)
b = a.tobytes()
print(b)
c = np.frombuffer(b, dtype=np.float16, count=1)
print(c)

Result:

b'\xf0<'
[1.234]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM