我使用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中运行时得到的输出
您提供了一个重复计数,但实际上需要1个解码的浮点(您尝试在这里解码4个浮点)
它在python2中工作,可能是因为python早期版本(struct allows repeat spec. without a format specifier)中的一个bug
应该会成功的。在
相关问题 更多 >
编程相关推荐