2

Using a Raspi 2 B, I want to output serial data to an intelligent display that requires the following format:
\xhh\xhh
where hh represents a hex value. The serial data is formed from various inputs which I concatenate using the following method:

SERDATA = ("\\x" + COMMAND + "\\x" + OBJECT)

printing SERDATA gives:

\\xhh\\xhh

Just printing "\\x" gives a single backslash and using only one escape character gives an invalid escape error, as expected. Where am I going wrong?

vaultah
  • 44,105
  • 12
  • 114
  • 143
Tog
  • 123
  • 4
  • That is not printing, it is repl output without printing which is the repr representation of your string. – Padraic Cunningham Apr 13 '15 at 16:21
  • The crux of the matter is that string escapes like `\xAB` are only valid when fully formed within a string constant; and they are dealt with when the program is 'compiled' (the string constant's value will actually contain the single char of value 0xAB, and not the escape sequence). So you can't build up string escapes with expressions like this. Well, you could using `eval` but I wouldn't recommend it. – greggo Apr 13 '15 at 16:48

2 Answers2

2

You're going wrong in thinking that's how you create bytes from hex codes.

SERDATA = (COMMAND + OBJECT).decode('hex')
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

You cannot make byte values like this; though you can use str.decode('string-escape') to get the resulting string:

>>> '\\x12\\x13'.decode('string-escape')
'\x12\x13'

It is not the recommended solution. Instead a better solution would be to use struct.pack instead, with 2 unsigned bytes as format, and values as integers:

>>> import struct
>>> COMMAND = 0x99
>>> OBJECT = 0x88
>>> SERDATA = struct.pack('=BB', COMMAND, OBJECT)
>>> SERDATA
'\x99\x88'

Using Python 3, and bytes, everything would be even slighty easier:

>>> COMMAND = 0x88
>>> OBJECT = 0x99
>>> SERDATA = bytes([COMMAND, OBJECT])
>>> SERDATA
b'\x88\x99'