Reputation: 3833
I have a program in python in which I want to receive a frame with some values. This values are sent by a xbee.
Xbee send a float splitted in 4 bytes by a union struct, something like this:
typedef union _data{
float f;
char s[4];
} myFloat;
So for example, 17.23 gives me 10, -41, -119, 65. So, I have to recover all these values in python and after I got 4, convert them into a float. What do I have to do since I read each one (serial.read()) to get the float resultant?
Those values will be received by python script and I want to join them again into a float. I read about struct in python but I am not good skill in python and I don't understand how it works.
I read bytes one by one using serial.read.
Any idea?
Upvotes: 2
Views: 4755
Reputation: 30581
If I understand correctly, you're getting the four integers [10, -41, -119, 65]
and you want to reassemble those into the original float. If so, the answer is already contained in @DSM's comments. Piecing the bits together:
>>> import struct
>>> x = [10, -41, -119, 65]
>>> struct.unpack('<f', struct.pack('4b', *x))[0]
17.229999542236328
Note that we're not getting exactly 17.23
here, because that number isn't exactly representable as a single-precision IEEE 754 binary float.
This sounds a little topsy-turvy, though: it should be easier to get the original bytes that to get 4 integers. How exactly are you getting the integer values? If you're using pyserial, couldn't you just do a read(4)
to get 4 bytes at once and then use struct.unpack
directly on the result of that? E.g., I'd expect something like this to work (simulated interpreter session):
>>> import struct
>>> x_bytes = ser.read(4) # (where ser is your Serial instance)
>>> x = struct.unpack('<f', x_bytes)[0]
>>> x
17.229999542236328
Upvotes: 6