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.
displaying byte data with REPL
Re: displaying byte data with REPL
Hi,
Here are a couple of ways off the top of my head using generators. The * converts the generator into *args.
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
-
- Posts: 847
- Joined: Mon Nov 20, 2017 10:18 am
Re: displaying byte data with REPL
Most of the time I use ustruct.unpack to unpack the bytes from serial in to what ever they suppose to be.
-
- Posts: 169
- Joined: Fri Aug 19, 2016 11:55 am
Re: displaying byte data with REPL
Code: Select all
>>> import ubinascii
>>> ubinascii.hexlify(b'9\x9f', ' ')
b'39 9f'