Python Bytearray Printing

Question:

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'nx91x8cxbcxd4xc6xd2x19x98x14xx0f1q!xdc|Cxaexe0xdcxf1xf1')

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…)

Asked By: panoptical

||

Answers:

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

Answered By: axblount
>>> x = bytearray(b'nx91x8cxbcxd4xc6xd2x19x98x14xx0f1q!xdc|Cxaexe0
xdcxf1xf1')
>>> import binascii
>>> print binascii.hexlify(x)
0a918cbcd4c6d2199814780f317121dc7c43aee0dcf1f1

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

Answered By: Lelouch Lamperouge

Use bytes.hex()

>>> x = bytearray([0x01,0x02,0xff])
>>> print(x.hex())
0102ff
Answered By: hongse

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'x00x01x02x03x04x05x06x07x08t')
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9
Answered By: Shreyas Murali
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.