Question

In Python 3.3 I need to convert an integer into the middle of three bytes to send it over a serial connection.

That is, I need to have a value of: b'\x4c\x00\x46', except that the \x00 byte will need to take the single-byte value of an integer variable that may vary from 0 to 255. I thought chr(value) would work, but that gives a string rather than a byte.

For example, if value is 255, I want to get b'\x4c\xff\x46'.

Was it helpful?

Solution

Using bytearray:

>>> b'\x4c\x00\x46'
b'L\x00F'
>>> a = bytearray(b'\x4c\x00\x46')
>>> a[1] = 255
>>> a
bytearray(b'L\xffF')
>>> bytes(a)
b'L\xffF'

You can also use list in place of bytearray. But using list does not work in Python 2.x.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top