struct.unpack with bytearray's

时光毁灭记忆、已成空白 提交于 2019-12-19 04:12:59

问题


I wrote an application that uses struct.unpack on byte arrays. Running it on my machine using python 2.7.5 it works well:

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

however, I tried to use it with a python version 2.7.3 I got an exception:

error: unpack requires a string argument of length 8

I need to explicitly cast the bytearray to string before unpacking it. Is this related to the python version change? the struct manual says nothing about this.. I would like to avoid doing all the casting, is there any way around this?


回答1:


As you have noticed, this is related to Python version. Apparently struct.unpack was fixed or extended after version 2.7.3.

If your script must work with both version 2.7.5 and 2.7.3 and you have found a way to make it run on both versions (by casting to string) then you can put your workaround code along with the call to struct.unpack into a function and call this function instead of doing directly the casting and calling of struct.unpack wherever you need to do it. This way your code will stay elegant, short and DRY.




回答2:


Also, you can wrap bytearray object with bytes:

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

It works on Python3 too.



来源:https://stackoverflow.com/questions/20612587/struct-unpack-with-bytearrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!