Reputation: 87
Assuming, I have a list bites with constant length
>>> chunk = [b'\xd0', b'\x00', b'\xd5', b'\x00', b'\xdf', b'\x00', b'\xaa', b'U']
>>> print(type(chunk))
<class 'list'>
>>> print(chunk)
[b'\xd0', b'\x00', b'\xd5', b'\x00', b'\xdf', b'\x00', b'\xaa', b'U']
And I want to get a single int from it, which could be done this way:
>>> a = int.from_bytes(chunk[2], byteorder='little')
>>> b = int.from_bytes(chunk[3], byteorder='little')
>>> decoded = a * 256 + b
>>> print(decoded)
213
How do I use struct.unpack
for that purpose?
Several ways I failed:
>>> print(struct.unpack('<xxHxxxx', chunk))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'list'
>>> tmp = bytes(chunk)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bytes' object cannot be interpreted as an integer
>>> tmp = bytes([chunk])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object cannot be interpreted as an integer
>>> tmp = bytearray(chunk)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bytes' object cannot be interpreted as an integer
The initial motivation was to check if struct.unpack
is any faster then already working code. But now I want to figure out the right way to use it.
Oh, and if there is any more efficient way, I would be glad to know that too!
Upvotes: 0
Views: 2395
Reputation: 5702
The issue is in how you convert a list
of bytes to bytes
. You can do this with b''.join(list)
and then apply your struct unpack.
Example:
>>> import struct
# your list of bytes
>>> lst = [b'\xd0', b'\x00', b'\xd5', b'\x00', b'\xdf', b'\x00', b'\xaa', b'U']
# Convert into `bytes`
>>> bts = b''.join(lst)
# Unpack
>>> print(struct.unpack('<xxHxxxx', bts))
(213,)
Note that you can also unpack the returned tuple with:
>>> (a,) = struct.unpack('<xxHxxxx', bts)
>>> a
213
Upvotes: 1