7

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

Ashok
  • 71
  • 1
  • 1
  • 2
  • 2
    Does this answer your question? [Why do I get an int when I index bytes?](https://stackoverflow.com/questions/28249597/why-do-i-get-an-int-when-i-index-bytes) – Mark Jan 24 '20 at 18:09
  • @MarkMeyer that doesn't answer the question. It simply explains how bytes objects work. – Martin May 08 '20 at 21:58

1 Answers1

2

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
prusswan
  • 6,853
  • 4
  • 40
  • 61