Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Bytearray Printing

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

like image 901
panoptical Avatar asked Jun 13 '13 17:06

panoptical


People also ask

How do I print a Bytearray?

You can simply iterate the byte array and print the byte using System. out. println() method.

What does Bytearray return Python?

bytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256. Returns: Returns an array of bytes of the given size. source parameter can be used to initialize the array in few different ways.


2 Answers

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

like image 105
Lelouch Lamperouge Avatar answered Oct 09 '22 02:10

Lelouch Lamperouge


Use bytes.hex()

>>> x = bytearray([0x01,0x02,0xff])
>>> print(x.hex())
0102ff
like image 15
hongse Avatar answered Oct 09 '22 01:10

hongse