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?

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.