How to let ASCII coded hexadecimals in an array to be treated as hexadecimals and not as characters in a string by Python? -


in [301]: string_to_write out[301]: '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0d'  in [302]: len(string_to_write) out[302]: 72  in [303]: thestring="\x01\x53\x38\x43\x43\x33\x46\x46\x30\x30\x30\x30\x30\x30\x31\x32\x31\x0d"  in [304]: print thestring s8cc3ff000000121  in [305]: len(thestring) out[305]: 18 

i need use serial port communicate device , need write string port. entered thestring through keyboard while used loop write each of hexadecimal characters string_to_write. need convert string_to_write thestring. how make python identify groups of 4 characters each hexadecimal.

you need chop string_to_write strings of length 4, convert strings integer, convert each of integers characters. here's efficient way in python 2 (a different approach needed in python 3). note code assumes of hex codes contain 4 chars, leading 0x. script uses binascii.hexlify print output data in convenient format.

from binascii import hexlify  def hex_to_bin(s):     return ''.join([chr(int(''.join(u), 16)) u in zip(*[iter(s)] * 4)])  s2w = '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0d' thestring = "\x01\x53\x38\x43\x43\x33\x46\x46\x30\x30\x30\x30\x30\x30\x31\x32\x31\x0d"  out = hex_to_bin(s2w) print repr(thestring) print repr(out) print hexlify(out) print thestring == out 

output

'\x01s8cc3ff000000121\r' '\x01s8cc3ff000000121\r' 01533843433346463030303030303132310d true    

Comments