gpt4 book ai didi

python - 为什么将 struct.unpack 与 bytearray 一起使用的相同代码在 Python 2.7.3 中引发异常,但在 2.7.5 中却没有?

转载 作者:行者123 更新时间:2023-11-28 20:46:33 24 4
gpt4 key购买 nike

我编写了一个在字节数组上使用 struct.unpack 的应用程序。使用 Python 2.7.5 在我的机器上运行它运行良好:

>>> data
bytearray(b'\x07\x00\x00\x00\x00\x00\x00\x00')
>>> struct.unpack("<Q", data)
(7,)

但是,我尝试将它与 Python 版本 2.7.3 一起使用时出现异常:

error: unpack requires a string argument of length 8

我需要在解包之前将字节数组显式转换为字符串。这与Python版本更改有关吗? struct manual对此只字未提。我想避免进行所有转换,有什么办法可以解决这个问题吗?

最佳答案

此外,您可以用字节包装 bytearray 对象:

>>> data
bytearray(b'\x07\x00\x00\x00\x00\x00\x00\x00')
>>> struct.unpack("<Q", bytes(data))
(7,)

它也适用于 Python3。

关于python - 为什么将 struct.unpack 与 bytearray 一起使用的相同代码在 Python 2.7.3 中引发异常,但在 2.7.5 中却没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20612587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com