binary16 in Python
Asked Answered
C

3

5

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?

Clementius answered 18/7, 2010 at 4:15 Comment(0)
P
4

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
Persimmon answered 18/7, 2010 at 4:42 Comment(0)
T
2

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.

Telex answered 18/7, 2010 at 4:25 Comment(0)
B
1

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).

Bolen answered 18/7, 2010 at 4:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.