Search code examples
pythonstructfloating-pointformatpacking

binary16 in Python


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?


Solution

  • 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