floating point - Converting a float in chars to float (PYTHON) -
i have program in python in want receive frame values. values sent xbee.
xbee send float splitted in 4 bytes union struct, this:
typedef union _data{ float f; char s[4]; } myfloat;
so example, 17.23 gives me 10, -41, -119, 65. so, have recover these values in python , after got 4, convert them float. have since read each 1 (serial.read()) float resultant?
those values received python script , want join them again float. read struct in python not skill in python , don't understand how works.
i read bytes 1 one using serial.read.
any idea?
if understand correctly, you're getting 4 integers [10, -41, -119, 65]
, want reassemble original float. if so, answer contained in @dsm's comments. piecing bits together:
>>> import struct >>> x = [10, -41, -119, 65] >>> struct.unpack('<f', struct.pack('4b', *x))[0] 17.229999542236328
note we're not getting exactly 17.23
here, because number isn't representable single-precision ieee 754 binary float.
this sounds little topsy-turvy, though: should easier original bytes 4 integers. how getting integer values? if you're using pyserial, couldn't read(4)
4 bytes @ once , use struct.unpack
directly on result of that? e.g., i'd expect work (simulated interpreter session):
>>> import struct >>> x_bytes = ser.read(4) # (where ser serial instance) >>> x = struct.unpack('<f', x_bytes)[0] >>> x 17.229999542236328
Comments
Post a Comment