【问题标题】:Converting BInary Block to Float将二进制块转换为浮点数
【发布时间】:2017-06-24 12:41:02
【问题描述】:

我正在使用 Python 将二进制数据块转换为其等效的浮点数据。我编写的代码在 Python 2.7 版中运行良好,但在 Python 3.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&û

第一个字节总是#,后面跟着一个数字,表示后面的字节数是Number,在这种情况下是2,所以后面是20。之后是真正的数据。每次读取长度为 4 个字节,并使用 little endian 格式转换为浮点数。

在 Python 2.7 中运行时的输出:

(1510, (-5.711601726275634e+25,))
(1520, (-246.98333740234375,))
(1530, (8723971440640.0,))
(1540, (-2.9736910156508145e-10,))
(1550, (-1039662528.0,))

我在 Python 3.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 中运行时得到的输出

【问题讨论】:

    标签: python python-3.x python-2.7 raspberry-pi3 raspbian


    【解决方案1】:

    您提供了重复计数,但您实际上需要 1 个解码的浮点数(您在这里尝试解码 4 个浮点数)

    它在 python 2 中工作,可能是因为旧版本的 python (struct allows repeat spec. without a format specifier) 中的一个错误

    measurement = struct.unpack('<f', byte)
    

    应该可以解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      • 2011-04-26
      • 2021-07-30
      • 2017-02-23
      • 1970-01-01
      相关资源
      最近更新 更多