[Numpy-discussion] Custom floating point representation to IEEE 754 double

Daniele Nicolodi daniele at grinta.net
Tue Feb 25 06:08:15 EST 2014


I'm dealing with an instrument that transfers numerical values through
an RS232 port in a custom (?) floating point representation (56 bits, 4
bits exponent and 52 bits significand).

Of course I need to convert this format to a standard IEEE 754 double to
be able to do anything useful with it.  I came up with this simple code:

  def tofloat(data):
      # 56 bits floating point representation
      # 4 bits exponent
      # 52 bits significand
      d = frombytes(data)
      l = 56
      p = l - 4
      e = int(d >> p) + 17
      v = 0
      for i in xrange(p):
          b = (d >> i) & 0x01
          v += b * pow(2, i - p + e)
      return v

where frombytes() is a simple function that assembles 7 bytes read from
the serial port into an integer for easing the manipulation:

  def frombytes(bytes):
      # convert from bytes string
      value = 0
      for i, b in enumerate(reversed(bytes)):
          value += b * (1 << (i * 8))
      return value

I believe that tofloat() can be simplified a bit, but except
optimizations (and cythonization) of this code, there is any simpler way
of achieving this?

Thanks. Cheers,

More information about the NumPy-Discussion mailing list