python - Convert string into hex to send for serial communication -
i have string numbers 5:240
. have send numbers string hex representation. number must in range of 2 bytes. but, want send exact representation on serial port '\x00\x05\x00\xf0'
. can me out on this?
i have tried following snippets no success:
b='5:240' b = b.split(':') in range(len(b)): print hex(int(b[i])) print len(hex(int(b[i])))
result:
0x5 3 0xf0 4
output shows hex conversion not possible me send on serial port, cause length varying. can resolve issue?
you can use hexadecimal format specifier, x
:
def word_hex(w): = int(w / 256) b = w % 256 return "{0:#0{1}x}{2:#0{3}x}".format(a,4,b,4).replace("0x", "\\x") b='5:240' b = b.split(':') in b: print(word_hex(int(i)))
prints
\x00\x05 \x00\xf0
Comments
Post a Comment