【问题标题】:How to convert a byte array to float in Python如何在 Python 中将字节数组转换为浮点数
【发布时间】:2019-05-31 13:59:12
【问题描述】:

我有一个字节数组,它最初是从 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 

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

【问题讨论】:

    标签: python floating-point endianness


    【解决方案1】:

    显然,编码该值的 Scala 代码使用的字节顺序与解码它的 Python 代码不同。

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

    在 Python 中,您可以使用 &gt;f&lt;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,)
    

    【讨论】:

    • 来自 Java ByteBuffer 文档:“字节缓冲区的初始顺序始终为 BIG_ENDIAN。”
    【解决方案2】:

    这可能是因为字节序编码。

    你应该试试大端:

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

    或小端:

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

    【讨论】:

      【解决方案3】:

      取决于你的字节数组。

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

      那么这应该工作: floatvar=float(byte_array_of_old_float)

      在我的例子中,字节数组来自 MariaDB 选择调用,我进行了类似的转换。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-21
        • 1970-01-01
        • 2013-10-20
        • 2012-11-08
        • 1970-01-01
        相关资源
        最近更新 更多