Search code examples
pythonhexasciidecode

Display hex data from serial port in print function


I receive data from serial port. It is not ASCII data (like from putty), but hex data from modbus rtu line (for example there is 0103AABBCCDD816E data on the line, where 01 is one byte in raw hex, 03 is another byte in raw hex... etc)

I am using python 3.6

I need to simply print as 0103AABBCCDD816E

I tried this code:

rx_raw = ser.read(8)
rx=binascii.hexlify(bytearray(rx_raw))
print("raw:  ")
print(rx_raw)   # gives:  b'\x01\x03\xaa\xbb\xcc\xdd\x81n'
print("\n")
print("hexiflied:  ")
print(rx)       # gives: b'0103aabbccdd816e'

binascii.hexlify(bytearray(rx_raw)) is almost what I need, but I need to get rid of b' '.


Solution

  • If you want to convert a binary string to a normal string you should decode it:

    b = b'0103aabbccdd816e'
    s = b.decode('ascii')
    
    print(b, s, s.upper())
    # b'0103aabbccdd816e' 0103aabbccdd816e 0103AABBCCDD816E
    

    From the docs:

    bytes.decode(encoding="utf-8", errors="strict")
    bytearray.decode(encoding="utf-8", errors="strict")

    Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.