0

I read UART port with this:

print ("Attempt to Read") readOut = serial_port.readline() time.sleep(1) in_hex = hex(int.from_bytes(readOut,byteorder='big')) print ("Reading: ", in_hex) 

and then it gives me output e.g. like:

Attempt to Read Reading: 0x6011401011403 

So there is one leading zero missing before number 6. I can't find a way to add it without specifying in the code the length of the whole string (and I don't want to do that, becasue the string can have variable length e.g. like 0x056822). Could you please help?

2
  • What is readOut in this example? What makes you know a leading 0 is missing? Commented Mar 29, 2019 at 18:11
  • I read it from UART interface and in the above example readOut should have 7 bytes, so I would like to print it like: 0x06011401011403 Commented Mar 29, 2019 at 18:14

2 Answers 2

1

You could inject a zero after 0x when the number of characters is odd:

if len(in_hex)%2: in_hex = in_hex.replace("0x","0x0") 
Sign up to request clarification or add additional context in comments.

1 Comment

Omg, simple and clever. I definitely should take a break today. Thank you!
0

Even number of digits is guaranteed if you convert each byte to two characters:

hexstr = ''.join(format(b,'02x') for b in bytesequence) 

Just prepend "0x" if you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.