On 25 February 2014 11:08, Daniele Nicolodi <dani...@grinta.net> wrote: > 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?
My first approach would be that if you have an int and you want it as bits then you can use the bin() function e.g.: >>> bin(1234) '0b10011010010' You can then slice and reconstruct as ints with >>> int('0b101', 2) 5 Similarly my first port of call for simplicity would be to just do float(Fraction(mantissa, 2**exponent)). It doesn't really lend itself to cythonisation but it should be accurate and easy enough to understand. Oscar _______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion