displaying byte data with REPL

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
smhodge
Posts: 86
Joined: Tue Jan 22, 2019 2:16 am
Location: Kirkland, WA, USA

displaying byte data with REPL

Post by smhodge » Sun Sep 15, 2019 2:33 am

I'm using REPL to test I2C code. It seems to work fine except that the bytes returned from the device get displayed as a string with a mixture of formats: ascii characters if a "printable" ascii character, otherwise hex notation. For example:
>>> i2c.send(0,69)
>>> i2c.recv(2,69)
b'9\x9f'
I know that the returned bytes are 0x39 0x9F. So the 0x39 is getting converted to the ascii character "9". This makes testing time consuming -- I have to have an ASCII table handy. Is there a way to force the string to always be displayed in hex? I'm sure this is some basic Python stuff and I've searched high and low but can't find out how to deal with this, so any help would be appreciated! Thanks.

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: displaying byte data with REPL

Post by jimmo » Sun Sep 15, 2019 3:43 am

Hi,

Here are a couple of ways off the top of my head using generators. The * converts the generator into *args.

Code: Select all

data = some bytes / bytearray
print(*(hex(b) for b in data))   # simple but doesn't zero-pad
print(*('0x{:02x}'.format(b) for b in data))   # more control over formatting

OutoftheBOTS_
Posts: 847
Joined: Mon Nov 20, 2017 10:18 am

Re: displaying byte data with REPL

Post by OutoftheBOTS_ » Sun Sep 15, 2019 8:55 am

Most of the time I use ustruct.unpack to unpack the bytes from serial in to what ever they suppose to be.

Christian Walther
Posts: 169
Joined: Fri Aug 19, 2016 11:55 am

Re: displaying byte data with REPL

Post by Christian Walther » Sun Sep 15, 2019 9:19 am

Code: Select all

>>> import ubinascii
>>> ubinascii.hexlify(b'9\x9f', ' ')
b'39 9f'

Post Reply