Ashok
Ashok

Reputation: 81

Python 3.8 Struct unpacking - struct.error: unpack requires a buffer of 1 bytes

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

Upvotes: 8

Views: 13292

Answers (1)

prusswan
prusswan

Reputation: 7091

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

Upvotes: 3

Related Questions