python 2.7 - 将浮点数转换为字节并循环遍历字节

python 2.7 - converting float to bytes and looping through the bytes

我正在尝试通过串行方式将浮点数作为一系列 4 个字节发送。 我有看起来像这样的有效代码:

ser.write(b'\xcd') #sending the byte representation of 0.1
ser.write(b'\xcc')
ser.write(b'\xcc') 
ser.write(b'\x3d')

但我希望能够发送任意浮点数。

我还希望能够单独检查每个字节,这样就不行了,例如:

bytes = struct.pack('f',float(0.1))
ser.write(bytes)

因为我要检查每个字节。

我正在使用 python 2.7 我该怎么做?

您可以使用struct模块将浮点数打包为二进制数据。然后遍历 bytearray 的每个字节并将它们写入输出。

import struct

value = 13.37  # arbitrary float 
bin = struct.pack('f', value)

for b in bin:
    ser.write(b)