Binary16 in Python

The module structis useful when you are trying to convert data to and from binary formats. However, I recently came across a file format specification that uses the binary16 floating-point format . I have looked at the Python documentation, but cannot find anything that could be converted to and from it. What would be the best way to convert this data to / from floating Python?

+5
source share
3 answers

You can do it roughly as if you did it in C - that is, I think, something 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
+4
source

python, python. struct, . , .

+2

A quick google search is http://packages.python.org/bigfloat/ , which says it has a context for handling floating point numbers binary16. However, I am not familiar with the package itself, so I could not tell you anything about how to use it (at least not more than that, you can read yourself in the documentation).

+1
source

All Articles