How can I create byte values from integers in Python?
19,705
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,))
Related videos on Youtube
Author by
mattdee123
Updated on June 25, 2022Comments
-
mattdee123 almost 2 years
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)
where "value" is an int that I read have read. The problem is, when I send this, it sends the character value, not the actual value (it sends the byte value 31 for the number 5, since that is the unicode position for it, I believe)
In reality, I want to be able to send it the character "\x05" for example. I guess my question is, how would I convert and int 5 to a char "\x05", or 37 to "\x37"
-
Jack O'Connor over 10 yearsThe first one fails, at least in Python 3, because it's trying to convert a string into bytes without specifying an encoding. (Note to readers, see joelonsoftware.com/articles/Unicode.html if encoding issues are new to you.) The second one works great. If the trailing comma used to create a tuple looks bad to you, you can also do something like
bytes([5])
. -
larsks about 8 yearsThe second one fails under Python 2, where
bytes((1,))
returns the string'(1,)'
. Under Python 3 this returnsb'\x01'
. So don't use either of these if you expect to support both Python 2 and 3.