Byte array as hex string

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
mcauser
Posts: 507
Joined: Mon Jun 15, 2015 8:03 am

Byte array as hex string

Post by mcauser » Sun Oct 01, 2017 12:29 pm

I have a byte array and when I print it, certain bytes are shown with ascii characters.
eg. bytearray(b'hello')

I'm trying to get it to display as bytearray(b'\x68\x65\x6c\x6c\x6f')

Is there a way to print it showing each byte in hex \xNN format?
Last edited by mcauser on Sun Oct 01, 2017 12:31 pm, edited 1 time in total.

User avatar
mcauser
Posts: 507
Joined: Mon Jun 15, 2015 8:03 am

Re: Byte array as hex string

Post by mcauser » Sun Oct 01, 2017 12:30 pm

Code: Select all

>>> data = bytearray(b'hello')
>>> print("".join("\\x%02x" % i for i in data))
\x68\x65\x6c\x6c\x6f
Close enough.

Post Reply