如何将字节数组转换为 Python 中的浮点数

How to convert a byte array to float in Python

我有一个字节数组,最初是从 Scala 中的浮点数组转换而来的。我需要将其转换回 Python.

中的浮点数组

这是我用来在 Scala 中转换浮点数组的代码:

val float_ary_len = float_ary.size
val bb = java.nio.ByteBuffer.allocate(float_ary_len * 4)
for(each_float <- float_ary){
    bb.putFloat(each_folat)
}
val bytes_ary = bb.array()

然后在Python中,我可以获得这个字节数组,我需要将它转换回浮点数组。

我在 Python 中尝试了以下代码,但它没有给我正确的浮动。

print(list(bytes_ary[0:4]))
#['\xc2', '\xda', 't', 'Z']

struct.unpack('f', bytes_ary[0:4])
# it gave me 1.7230105268977664e+16, but it should be -109.22725 

请告诉我如何获得正确的浮动?

可能是字节序编码的问题。

你应该试试大端:

struct.unpack('>f', bytes_ary[0:4])

或小端:

struct.unpack('<f', bytes_ary[0:4])

显然,对值进行编码的 Scala 代码使用与对其进行解码的 Python 代码不同的字节顺序。

确保在两个程序中使用相同的字节顺序(字节顺序)。

在 Python 中,您可以使用 >f<f 而不是 f 来更改用于解码值的字节顺序。参见 https://docs.python.org/3/library/struct.html#struct-alignment

>>> b = b'\xc2\xdatZ'
>>> struct.unpack('f', b)   # native byte order (little-endian on my machine)
(1.7230105268977664e+16,)
>>> struct.unpack('>f', b)  # big-endian
(-109.22724914550781,)

取决于您的字节数组。

如果 print(byte_array_of_old_float) returns bytearray(b'684210')

那么这应该有效: floatvar=float(byte_array_of_old_float)

在我的例子中,字节数组来自 MariaDB select 调用,我就是这样进行转换的。