How can I create byte values ​​from integers in Python?

Background: I need to send a numeric value as a byte to an external device, but I am facing a problem. My code:

ser=serial.Serial("COM3",9600, timeout=0)
ser.write(value)

      

where "value" is the int I read, read. The problem is, when I post this, it sends the character value, not the actual value (it sends byte value 31 for number 5, since that's the unicode position for it, I believe)

In fact, I want to be able to send it the character "\ x05", for example. I guess my question is how would I convert both int 5 to char "\ x05", or 37 to "\ x37"

+3


source to share


2 answers


Use the built-in function chr()

.

If you have a list of such integers that you need to send, you can use bytearray()

.



Alternatively, in newer versions of Python, you can simply use type byte

.

+8


source


you can use this.



bytes(chr(my_int))    # not strictly correct unless 0<=my_int<=255
bytes((my_int,))

      

+3


source







All Articles