32

I have an integer list in Python that should correspond to the following int values (which can be changed to hex byte values):

[10, 145, 140, 188, 212, 198, 210, 25, 152, 20, 120, 15, 49, 113, 33, 220, 124, 67, 174, 224, 220, 241, 241]

However, when I convert that list to a bytearray (using bytearray(nameOfList)), I get the following printout.

bytearray(b'\n\x91\x8c\xbc\xd4\xc6\xd2\x19\x98\x14x\x0f1q!\xdc|C\xae\xe0\xdc\xf1\xf1')

I can pull the correct values from this byte array, regardless of how it prints, but shouldn't the bytearray printout correspond to the hex values of the byte array? (I mean, it seems to mostly follow the hex values up until after \x0f, where it starts putting out gibberish...)

3
  • 1
    It looks fine to me. It's just rendering bytes as ASCII characters whenever possible. After \x0f you have 49='1' and 113='q', etc. asciitable.com
    – axblount
    Jun 13, 2013 at 17:50
  • 1
    Exactly ... It only represents non-printing characters as \x..
    – mgilson
    Jun 13, 2013 at 17:51
  • 1
    list(your_bytearray) == your_list
    – jfs
    Jun 13, 2013 at 17:53

4 Answers 4

39
>>> x = bytearray(b'\n\x91\x8c\xbc\xd4\xc6\xd2\x19\x98\x14x\x0f1q!\xdc|C\xae\xe0
\xdc\xf1\xf1')
>>> import binascii
>>> print(binascii.hexlify(x))
0a918cbcd4c6d2199814780f317121dc7c43aee0dcf1f1

Use binascii if you want all of it to be printed as a hex string

1
  • ...just what I needed.
    – uhoh
    Jan 31, 2018 at 11:17
18

Use bytes.hex()

>>> x = bytearray([0x01,0x02,0xff])
>>> print(x.hex())
0102ff
1
12

It looks fine to me. It's just rendering bytes as ASCII characters whenever possible. After 15=\x0f you have 49='1' and 113='q', etc.

See http://asciitable.com

1
  • Is there any way to switch this behavior off? It's so annoying when you are working with binary data.
    – Peter
    Aug 7, 2022 at 3:31
2

This is probably not very performant at large sizes, but I find this makes it easier to read:

buff = bytearray(list(range(10)))
print(buff)
print(", ".join(hex(b) for b in buff))

prints

bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t')
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.