8

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

asked Jan 24, 2020 at 17:55
2
  • 2
    Does this answer your question? Why do I get an int when I index bytes? Commented Jan 24, 2020 at 18:09
  • @MarkMeyer that doesn't answer the question. It simply explains how bytes objects work. Commented May 8, 2020 at 21:58

1 Answer 1

3

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
answered Feb 21, 2021 at 19:43
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.