struct.unpack with bytearray's

瘦欲@ 提交于 2019-12-01 00:55:25

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.

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.

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