Skip to content
Advertisement

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!

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

Result:

JavaScript

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

JavaScript

Result:

JavaScript

If you literally needed to turn the string you provided into an FP16:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement