2

I am trying to send a hexadecimal string to a serial port  and it has to be in the following format '\x02\x81....'  this is my code

from binascii import unhexlify
string='0281E1B1'
print unhexlify(string)

gives me  some randon symbols ?a+ instead of \x02\x81\xE1\xB1 I have python 2.7 so decode('hex') isnt working either

1 Answer 1

3

you are doing it right .... you just need to send it over the port

print repr(unhexlify(my_string))

my_serial.write(unhexlify(my_string))

#or 

my_serial.write(my_string.decode("hex"))

the problem is you cant just print random bytes( "\x##") to the terminal and expect to see something that makes sense ...the terminal displays characters it cannot decode a ? or like a diamond with a question mark

>>> '0281E1B1'.decode("hex")
'\x02\x81\xe1\xb1'
>>> print '0281E1B1'.decode("hex")
☻üß▒
>>> '0281E1B1'.decode("hex") == unhexlify('0281E1B1')
True

although for whatever weird reason my terminal didnt add any ? to that particular string

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for explaining! You are right it all works now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.