Jay Pinder Jay Pinder - 1 month ago 14
Python Question

Python - binascii.unhexlify and .decode("hex") return TypeError: Non-hexadecimal digit found

I've searched this extensively but cannot find a post that fixes this issue. I have a simple string that I've received from a modem of '82001B014042'. I want to disregard the preceding header of '82001B01' and decode the hex digits '4042'. My code is as follows;

rxHEX = ser.readline()
print rxHEX #82001B014042
rxData = rxHEX[8:] #4042
print rxData
#rxData = "4042"
rxData = rxData.decode("hex")
#rxData = binascii.unhexlify(rxData)
print rxData


Regardless if I use .decode("hex") or binascii.unhexlify(rxData) I receive TypeError: Non-hexadecimal digit found

If I un-hash
#rxData = "4042"
it returns @S which is what I'd expect.

Why won't it work from what is received from the modem string?

If I only have

rxHEX = ser.readline()
print rxHEX
rxData = rxHEX[8:]
print rxData
I recieve


The output is

82001F014042

4042

Answer

Because you're using .readline(), your string most likely contains a newline (or CRLF pair) at the end. Therefore, you should try rxData = rxHEX[8:].strip().