The struct
module is useful when you're trying to convert data to and from binary formats. However, recently I came across a file format specification that uses the binary16 floating point format. I looked through the Python documentation, but can't find anything that can convert to and from it. What would be the best way to convert this data to/from Python floats?
binary16 in Python
You can do it roughly like you'd do it in C -- i.e., I think, roughly like this...:
def tofloat(b16):
sign = -1 if b16 & 0x8000 else +1
expo = ( b16 & 0x7C00 ) >> 10
prec = b16 & 0x03FF
if expo == 0:
return sign * (2.0 ** -24) * prec
elif expo == 0x1F:
return sign * float('inf')
prec |= 0x0400
return sign * (2.0 ** (expo - 25)) * prec
This guy's blog post gives an implementation in both and python. He uses the struct
module, then decodes it manually. It is not all that complicated a conversion.
A quick Google search turned up http://packages.python.org/bigfloat/ which says it has a context for manipulation of binary16
floating-point numbers. I'm not familiar with the package myself, though, so I couldn't tell you anything about how to use it (at least, nothing more than you can read yourself in the documentation).
© 2022 - 2024 — McMap. All rights reserved.