如何使用Python将4个字节解释为32位浮点数 [英] How to interpret 4 bytes as a 32-bit float using Python
问题描述
我是Python语言的新手,很难做一些我可以很轻松地用C ++或Java做的事情,但是由于某种原因,似乎很难在Python中做。我在数组中有以下四个字节(按大端顺序):
I am sort of a novice to the Python language and am having a hard time doing something I could very easily do with C++ or Java but for some reason seems so convoluted to do in Python. I have the following four bytes in an array (in big endian order):
[0x64, 0xD8, 0x6E, 0x3F]
我已经事先知道这些字节代表什么。他们指定以下32位浮点数: 0.932989
I already know beforehand what these bytes represent. They specify the following 32-bit floating-point number: 0.932989
我需要执行哪些步骤Python(最好是v3.2.1,并且不使用额外的导入)将这4个字节解释为浮点数并将该数字存储在一个变量中,我可以将其作为32位浮点值进行操作?即因此我可以将其用作以下变量 myVar = 0.932989
What are the steps I need to perform using Python (preferably v3.2.1 and without using extra imports) to interpret those 4 bytes as that float and store that number in a variable which I can manipulate as a 32-bit floating-point value? I.e. so i can use it just as the following variable 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
的原始字节为浮点数,而是强制转换这些字节的整数表示,因此 z
包含 1064228964.0
而不是所需的值 0.932989
。可能有等同于 int.from_bytes
的东西可以用来执行此简单任务吗?也许类似 float.from_bytes
?
y
has the right expected integer interpretation of those bytes, which is 1064228964
, the problem comes when casting that to a 32-bit float
. Instead of casting the raw bytes of y
as a float, it casts the integer representation of those bytes, so z
contains 1064228964.0
instead of the desired value of 0.932989
. Is there maybe something equivalent to int.from_bytes
that I can use to perform this simple task? Perhaps something like float.from_bytes
?
推荐答案
有关详细信息,请参见 Python结构。对于您的特定问题:
For detail see Python Struct. For your specific question:
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将4个字节解释为32位浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!