Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Hex data

I am working with some hardware that can be controlled via hex commands. I already have some snippets of Python code I use for telnet control of other devices that use ASCII commands.

How do I go about sending hex commands? For instance, how would I modify skt.send('some ascii command\r') with hex value, and what's the best data type for storing those values?

Thanks.

like image 806
inbinder Avatar asked Aug 08 '12 13:08

inbinder


2 Answers

In Python 2, use string literals:

skt.send('\x12\r')

In Python 3, use bytes literals or bytes.fromhex:

skt.send(b'\x12\r')
skt.send(bytes.fromhex('12 0d'))

In either case, the bytearray type will probably be useful as it is a mutable (modifiable) type that you can construct with integers as well as a bytes literal:

skt.send(bytearray([0x02, 0x03, 0x00, 0x00, 0x05]))
like image 71
ecatmur Avatar answered Sep 29 '22 18:09

ecatmur


Under Python 3, you have the great bytes.fromhex() function as well.

>>> bytes.fromhex('AA 11 FE')
b'\xaa\x11\xfe'
>>> bytes.fromhex('AA11FE')
b'\xaa\x11\xfe'
like image 37
Jill-Jênn Vie Avatar answered Sep 29 '22 17:09

Jill-Jênn Vie