2

i have a python hexadecimal like this:

variable = b'\x80pu\xa6\x7f\xfe\xb9\x1d\xaf'

in python 2 if i do variable[0] i get '\x80' but in python 3 it converts into int for me and it return 128.

i guess i can try to convert the answers back to hexadecimal like this:

hex(variable[0])

but its a whole array and i might not be integers. i was looking for a better way to do this since:

hex() takes only integer and also it returns a string not the hexadecmial version

i want the actual x80 not 128

how would i do this?

code i am working with:

p = b'\x80pu\xa6\x7f\xfe\xb9\x1d\xaf'
f = struct.unpack('>B', p[0])[0]

TypeError: a bytes-like object is required, not 'int'

it works in python2 but not in python 3

  • `and it might not be integers` In python3 bytes is *defined* as a sequence of integers. It's hard to understand what a single bytes can be other than a value between 0 and 255. – Mark Jul 24 '20 at 14:35
  • Maybe, [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) is helpful here. – Mark Jul 24 '20 at 14:36
  • 1
    Does this answer your question? [What's the correct way to convert bytes to a hex string in Python 3?](https://stackoverflow.com/questions/6624453/whats-the-correct-way-to-convert-bytes-to-a-hex-string-in-python-3) – rfkortekaas Jul 24 '20 at 17:52

1 Answers1

0

I'm so glad I found your question - I just hit the same problem with python2 code that we were converting to python3. My solution to your problem was to use slices (which is covered by the SO question: Why do I get an int when I index bytes?).

Specifically for your code:

p = b'\x80pu\xa6\x7f\xfe\xb9\x1d\xaf'
f = struct.unpack('>B', p[0:1])[0]

Observe that I changed your expression p[0] (which evaluates to int in python3) to a 1-byte slice p[0:1] (which is of type <class 'bytes'>). By contrast, python2.7 considers p[0] as <type 'str'> and p[0:1] also as <type 'str'>.

Mark
  • 4,249
  • 1
  • 18
  • 27