pjaneck
pjaneck

Reputation: 13

Python pack string as ascii hex value

I have a problem (maybe in understanding) with the struct module and the pack method. I need to pack a message to communicate with a sensor. One value of this message is the ascii representation of an integer (in this case "0" and "3"), which is 48 and 51. The sensor only accepts hex values (in this case 30 and 33). But when I use pack('BB',48,51) it gives me '\x0003' back but I need '\x30\x33'. Is there a way to convert these two chars to "hex-binaries"?

Upvotes: 1

Views: 5319

Answers (2)

Anton Sutarmin
Anton Sutarmin

Reputation: 847

If it's not nessesary to use pack, you can use something like this:

'\\'+hex(48)[1:]

Upvotes: -1

gre_gor
gre_gor

Reputation: 6774

'\x30\x33' is the same as '03'

>>> import struct
>>> print struct.pack('BB', 48, 51)
03
>>> print '\x30\x33'
03
>>> '\x30\x33' == '03'
True

'\x30\x33' and '03' are different representation of the same thing.
'\x30\x33' is defined by their hex values and '03' by ASCII characters.

In the end both of them are an array of two bytes 48 (0x30) and 51 (0x33).

The sensor only accepts hex values

Sensor only accepts bytes, it depends how you need to encode the value.
Do you need to send a number 3 or a string "03"?

If it's a number you will need to send "\x03" or pack("B", 3).
If it's a string you just need to send "03".

Upvotes: 5

Related Questions