Python将字节数据的字符串repr转换为float数据

时间:2016-01-06 00:01:10

标签: python arrays string arduino byte

我通过一个用于表示3个浮点值的Web套接字发送了12个字节。另一个程序这样做:

float m_floatArray[3]; 
...
Serial.write((byte*) m_floatArray, 12); //12 b/c 3 floats at 4 bytes each

我在python程序中收到的数据如下所示:

#the data is printed from: received = ser.read(12)  
received = '\xe4C\x82\xbd-\xe4-\xbe&\x00\x12\xc0'

我想在我的python程序中实际执行此操作:

x = getFirstFloat(received)
y = getSecondFloat(received)
z = getThirdFloat(received)

如何解析我的数据?谢谢。

1 个答案:

答案 0 :(得分:2)

一个简短的例子:

>>> a,b,c = [random.random()*10 for i in range(3)]
>>> a
0.9446191909332258
>>> b
7.578277797297625
>>> c
8.061585451293366
>>> recieved = struct.pack('fff', a, b, c)
>>> recieved
'\x90\xd2q?@\x81\xf2@A\xfc\x00A'
>>> x,y,z = struct.unpack('fff', recieved)
>>> x
0.9446191787719727
>>> a
0.9446191909332258
>>> b
7.578277797297625
>>> y
7.578277587890625
>>> c
8.061585451293366
>>> z
8.061585426330566
>>>

请注意,您可能需要在byte order

中指定format string