hexadecimal numbers over UART

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
BL007
Posts: 16
Joined: Wed Sep 02, 2020 6:38 am

Re: hexadecimal numbers over UART

Post by BL007 » Tue Nov 03, 2020 9:21 am

Roberthh wrote:
Tue Nov 03, 2020 9:11 am
You tried hexlify instead of unhexlify.
OK, this works too.
I can't read. Sorry!

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: hexadecimal numbers over UART

Post by pythoncoder » Tue Nov 03, 2020 9:56 am

You may need to DIY. Assuming you really want hex: you wrote
Which function makes from '53006400C845' => b'\53\00\64\00\C8\45' or leastways from '53' => b'x53'?
b'\53 is not the same as b'x53'

You could do this:

Code: Select all

def foo(a):
    a = iter(a)
    res = ''
    try:
        while True:
            res = ''.join((res, '\\x', next(a), next(a)))
    except StopIteration:
        pass
    return res.encode()
answer = foo('53006400C845')
print(answer)
This produces

Code: Select all

b'\\x53\\x00\\x64\\x00\\xC8\\x45'
Note that the double slashes are artefacts, as demonstrated by:

Code: Select all

>>> for x in range(5):
...     print(chr(answer[x]))
...     
... 
\
x
5
3
\
Peter Hinch
Index to my micropython libraries.

Post Reply