Python/Simulink/MATLAB: 如何在Python中正确读取Simulink中的单类型4bytes数据?

Python/Simulink/MATLAB: How to properly read single-type 4bytes data from Simulink in Python?

我在 Simulink 中有一个程序可以通过 TCP-IP 发送一些值并在 Python 2.7 中读取它们。数据作为 "single" 值发送。 Python 中的代码读取 4 个字符串作为其 32 位长(长度为 4 的字符串)。

print "x0:", ord(data[0])
print "x1:", ord(data[1])
print "x2:", ord(data[2])
print "x3:", ord(data[3])

问题是,我在 Python 中得到的值与发送的值不同。

0.125 is read as x0: 62, x1: 0, x2: 0, x3: 0
13.65 is read as x0:65, x1=90, x2: 96, x3: 0
51.79 is read as x0:66, x1=79, x2: 42, x3: 128
113.4 is read as x0:66, x1=226, x2: 200, x3: 220

那么如何获得这些值...0.125、13.65、51.79、113.4...作为接收端的正确数字 (Python)?

使用 struct 解压您从网络中获取的 4 字节浮点数。

>>> import struct
>>> patt='!f'    # big-endian single-precision float, 4 bytes
>>> _0_125 = chr(62)+chr(0)+chr(0)+chr(0)
>>> struct.unpack(patt,_0_125)
(0.125,)   
>>> _13_65 = chr(65)+chr(90)+chr(96)+chr(0)
>>> struct.unpack(patt,_13_65)
(13.6484375,) 
>>> _51_79 = chr(66)+chr(79)+chr(42)+chr(128)
>>> struct.unpack(patt,_51_79)
(51.79150390625,)

这会给你一个元组,因为你传递给 unpack 的字节串中可能有多个数据项。

我不得不使用 chr() 从你的问题中重新创建字节串。如果你已经在 x 中有一个字节串,那么 struct.unpack(patt,x) 就可以了。

您以字节形式看到的数据似乎与您期望的值无关,因为它是 IEEE754 格式。数据是二进制的,字节边界没有意义:

  • 位 31: 符号(0 = 正,1 = 负)
  • 位 30 到 23: 指数,偏置 127
  • 位 22 到 0: 数字 1.f 的分数 f(其中.表示二进制小数点)