I am trying to unpack python struct in Python 3.8 and getting error
TypeError: a bytes-like object is required, not 'int'
. The same code works fine in Python 2.7
import struct
hexval= b'J\xe6\xe7\xa8\x002\x10k\x05\xd4\x7fA\x00\x04\n\x90\x1a\n'
aaT = struct.unpack('>H',hexval[4:6])
aa = aaT[0]
print("aa",aa)
bbT = struct.unpack(">B",hexval[12])
bb = bbT[0]&0x3 # just lower 2 bits
print("bb",bb)
Output:
aa 50
Traceback (most recent call last): File "./sample.py", line 9, in bbT = struct.unpack(">B",hexval[12]) TypeError: a bytes-like object is required, not 'int'
When i converted to byte
i get error like this.
Traceback (most recent call last): File "sample.py", line 9, in bbT = struct.unpack(">B",bytes(hexval[12])) struct.error: unpack requires a buffer of 1 bytes
How can i unpack this binary data
-
2Does this answer your question? Why do I get an int when I index bytes?Mark– Mark2020年01月24日 18:09:31 +00:00Commented Jan 24, 2020 at 18:09
-
@MarkMeyer that doesn't answer the question. It simply explains how bytes objects work.Martin– Martin2020年05月08日 21:58:59 +00:00Commented May 8, 2020 at 21:58
1 Answer 1
It is another of those changes related to data types going from Python 2 to 3. The reasoning is explained in the answer to Why do I get an int when I index bytes?
Just in case the answer is not obvious, to get the same result as in Python 2, do this instead:
bbT = struct.unpack(">B",hexval[12:13]) # slicing a byte array results in a byte array, same as Python 2