Jay Pinder
Jay Pinder

Reputation: 45

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

Upvotes: 3

Views: 25602

Answers (2)

nneonneo
nneonneo

Reputation: 179382

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().

Upvotes: 3

ShadowRanger
ShadowRanger

Reputation: 155323

readline doesn't strip trailing newlines. Use rsHEX.rstrip('\r\n') to remove trailing newlines on any OS, or rsHEX.strip() to just drop all leading and trailing whitespace of any kind.

Upvotes: 0

Related Questions