Skip to content Skip to sidebar Skip to footer

How Can I Create Byte Values From Integers In Python?

Background: I need to send a numerical value as a byte to an external device, but I have run into a problem. My code is: ser=serial.Serial('COM3',9600, timeout=0) ser.write(value)

Solution 1:

Use the built-in function chr().

If you have a list of such integers you need to send, you might consider using a bytearray().

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


Solution 2:

you can use this..

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

Post a Comment for "How Can I Create Byte Values From Integers In Python?"