Decimal to hexadecimal in python

So, I have some kind of uninformed (maybe?) Question. This is the first time I am working with recording on a serial device. I have a frame [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, X, Y] that I need to send. X and Y are checksum values. My understanding of using the pyserial module is that I need to convert this frame to a string representation. Good, good, but I'm confused about the format in which things should be. I tried to do

a = [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, X, Y]
send = "".join(chr(t) for t in a)

But my confusion comes from the fact that X and Y when using chr are converted to strange strings (assuming they are ascii). For example, if X is 36, chr (x) is "$" instead of "\ x24". Is there a way that I can get a string representing the value "\ xnn" instead of ascii code? What bothers me is that 12 and 7 are correctly converted to "\ x0b" and "\ x07". Did I miss something?

Update:
Perhaps I do not quite understand how serial recordings are performed or what my device expects from me. This is the part of my C code that works:


fd=open("/dev/ttyS2",O_RDWR|O_NDELAY);
char buff_out[20]
//Next line is psuedo
for i in buff_out print("%x ",buff_out[i]); // prints b 0 0 0 0 0 0 0 9 b3 36 
write(fd,buff_out,11);  
sleep()
read(fd,buff_in,size);
for i in buff_in print("%x ",buff_in[i]); // prints the correct frame that I'm expecting


Python:



frame = [11, 0, 0, 0, 0, 0, 0, 0, 9] + [crc1, crc1]

senddata = "".join(chr(x) for x in frame)



IEC = serial.Serial(port='/dev/ttyS2', baudrate=1200, timeout=0)
IEC.send(senddata)

IEC.read(18) # number of bytes to read doesn't matter, it always 0

? , , , . , serial.send() ?

+5
4

ASCII, , , \x??. , :

>>> '\x68\x65\x6c\x6c\x6f'
'hello'

, Python 2.6 , bytearray, ord struct.

>>> vals = [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, 36, 100]
>>> b = bytearray(vals)
>>> b
bytearray(b'\x0c\x00\x00\x00\x00\x00\x00\x00\x07\x00$d')

str ( bytes Python 3) bytearray, .

>>> str(b)
'\x0c\x00\x00\x00\x00\x00\x00\x00\x07\x00$d'
>>> b[0]
12
>>> b[-1]
100

Python, - , , ...

+3

ASCII- 36 - '$'. ASCII. Python , ( ..).

- - , Python escape char ASCII.

struct, .

+1

, struct.

>>> import struct
>>> struct.pack('>B', 12)
'\x0c'
>>> vals = [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0xa, 0xb]
>>> ''.join(struct.pack('>B', x) for x in vals)
'\x0c\x00\x00\x00\x00\x00\x00\x00\x07\x00\n\x0b'
0

, : send - , : , (a).

, send, :

import binascii
print binascii.hexlify(send)

print ''.join(r'\x%02x' % ord(char) for char in send)

( \x).

, repr(send), send, ASCII: 65 "A", 12 - "\ x0c". , Python, , , : "Hello", \x48\x65\x6c\x6c\x6f!

0

All Articles