Am 25.02.2014 um 12:08 schrieb Daniele Nicolodi <dani...@grinta.net>:
> Hello, > > 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? > I have no ready made code at hand, but an alternative approach would be to use the struct module and assemble a standard double from your data by fiddling on the byte level. Most of the data you can just copy, your 4 bit exponent needs to be expanded (appending zeros?) to 12 bit. But since your data comes from a serial port, efficiency might not be important at all. Gregor _______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion