简体   繁体   English

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

[英]How to convert a byte array to float in Python

I have a byte array, which originally was converted from a float array in Scala.我有一个字节数组,它最初是从 Scala 中的浮点数组转换而来的。 I need to convert it back to a float array in Python.我需要将它转换回 Python 中的浮点数组。

This is the code I used to convert the float array in Scala:这是我用来在 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()

Then in Python, I can get this byte array and I need to convert it back to a float array.然后在 Python 中,我可以获得这个字节数组,我需要将它转换回一个浮点数组。

I have tried the following code in Python, but it didn't give me the right float.我在 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 

Please let me know how should I get the right float?请让我知道我应该如何获得正确的浮点数?

Apparently the Scala code that encodes the value uses a different byte order than the Python code that decodes it.显然,对值进行编码的 Scala 代码使用与解码它的 Python 代码不同的字节顺序。

Make sure you use the same byte order (endianness) in both programs.确保在两个程序中使用相同的字节顺序(字节序)。

In Python, you can change the byte order used to decode the value by using >f or <f instead of f .在 Python 中,您可以使用>f<f而不是f来更改用于解码值的字节顺序。 See https://docs.python.org/3/library/struct.html#struct-alignment .请参阅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,)

It could be because of the endian encoding.这可能是因为字节序编码。

You should try big endian:你应该尝试大端:

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

or little endian:或小端:

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

Depends on your byte array.取决于您的字节数组。

if print(byte_array_of_old_float) returns bytearray(b'684210')如果print(byte_array_of_old_float)返回bytearray(b'684210')

then this should work: floatvar=float(byte_array_of_old_float)那么这应该有效: floatvar=float(byte_array_of_old_float)

In my case the byte array came from a MariaDB select call, and I did the conversion like that.在我的情况下,字节数组来自 MariaDB 选择调用,我进行了这样的转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM