我是 Python 语言的新手,我很难做一些我可以用 C++ 或 Java 轻松完成的事情,但由于某种原因,在 Python 中做起来似乎很复杂。我在数组中有以下四个字节(按大端顺序):
[0x64, 0xD8, 0x6E, 0x3F]
我事先已经知道这些字节代表什么。它们指定以下 32 位 float :0.932989
我需要使用 Python(最好是 v3.2.1 并且不使用额外的导入)执行哪些步骤来将这 4 个字节解释为 float 并将该数字存储在一个变量中,我可以将其作为 32 位 float 进行操作-点值? IE。所以我可以像下面的变量一样使用它 myVar = 0.932989
我试过:
x = [0x64, 0xd8, 0x6e, 0x3f]
y = int.from_bytes(x, byteorder='little', signed=False) #interpret bytes as an unsigned little-endian integer (so far so good)
z = float(y) #attempt to cast as float reinterprets integer value rather than its byte values
y
对这些字节有正确的预期整数解释,即 1064228964
,将其转换为 32 位 float
时会出现问题>。它不是将 y
的原始字节转换为 float ,而是转换这些字节的整数表示,因此 z
包含 1064228964.0
而不是所需的0.932989
的值。是否有等同于 int.from_bytes
的东西可以用来执行这个简单的任务?也许像 float.from_bytes
这样的东西?
最佳答案
有关详细信息,请参阅 Python Struct .对于您的具体问题:
import struct
# if input is string, per @robyschek will fail on python 3
data=b'\x64\xd8\x64\x3f'
print struct.unpack('<f', data) #little endian
print struct.unpack('>f', data) # big endian
#your input
list1=[0x64, 0xD8, 0x6E, 0x3F]
# aa=str(bytearray(list1)) # edit: this conversion wasn't needed
aa= bytearray(list1)
print struct.unpack('<f', aa)
输出:
(0.8939268589019775,)
(3.193376169798871e+22,)
(0.9329893589019775,)
关于python - 如何使用 Python 将 4 个字节解释为 32 位 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37093485/