将二进制块转换为F

2024-03-29 04:49:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python将二进制数据块转换为其等效的浮点数据。我编写的代码在Python2.7版中运行良好,但在Python3.4中同样失败

import sys
import struct

start = 1500
stop = 1600
step = 10

with open("/home/pi/Desktop/Output.bin", "rb") as f:
    byte = f.read(2)
    readNext = int(byte[1])
    byte = f.read(int(readNext))
    byte = f.read(4)

    while (len(byte) > 3):
        measurement = struct.unpack('<f4', byte)
        start = start + 10
        print(start, measurement)
        byte = f.read(4)

二进制块数据如下所示

“#220&;lt;ŒvçýTýz÷wΔ

第一个字节总是#,后面跟一个数字,表示后面的字节数,即数字,在本例中是2,所以后面跟着20。接下来就是真实的数据。每次读取4字节长,并使用little-endian格式转换成float。在

在Python 2.7中运行时的输出:

^{pr2}$

我在Python3.4中运行的代码:

import sys
import struct

start = 1500
stop = 1600
step = 10

with open("/home/pi/Desktop/Output.bin", "rb") as f:
    byte = f.read(2)
    byte = byte.decode('UTF-8') #I had to convert to read the Byte
    readNext = byte[1] # Reading the First Digit
    byte = f.read(int(readNext)) # Skip the Integer values
    byte = f.read(4) # The Actual Data

    while (len(byte) > 3):
        measurement = struct.unpack('<f4', byte)
        start = start + 10
        print(start, measurement)
        byte = f.read(4)

错误:

Traceback (most recent call last):
  File "/home/pi/Desktop/MultiProbe/bin2float.py", line 17, in <module>
    measurement = struct.unpack('<f4', byte)
struct.error: repeat count given without format specifier

如何修改它以获得类似于在Python2.7中运行时得到的输出


Tags: the数据importhomereadpibytestart