Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the same code using struct.unpack with a bytearray raise an exception in Python 2.7.3 but not in 2.7.5?

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 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?

like image 714
WeaselFox Avatar asked Jan 31 '26 07:01

WeaselFox


1 Answers

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.

like image 121
Alex Lisovoy Avatar answered Feb 01 '26 21:02

Alex Lisovoy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!