我通过网络套接字发送了 12 个字节,用于表示 3 个浮点值。另一个程序执行此操作:
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)
如何解析我的数据?
一个简短的例子:
>>> 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
>>>