The Python Oracle

Python 3 - on converting from ints to 'bytes' and then concatenating them (for serial transmission)

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping

--

Chapters
00:00 Question
02:47 Accepted answer (Score 7)
03:53 Thank you

--

Full question
https://stackoverflow.com/questions/1864...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #serialport #typeconversion #byte

#avk47



ACCEPTED ANSWER

Score 7


You are confusing Python byte literal syntax here; you do not need to generate the literal syntax, just the byte value; the bytes() type accepts a sequence of integers too:

>>> bytes([255])
b'\xff'

Applied to your code:

SET_BG_COLOR = b'\xAA\x03\x03'
for r in range(0,255):
    red = bytes([r])
    blue = bytes([255 - r])
    ser.write(SET_BG_COLOR + blue + b'\x00' + red + b'\xC3') #BGR format

or, simpler still:

SET_BG_COLOR = [0xAA, 0x03, 0x03]
for r in range(0,255):
    ser.write(bytes(SET_BG_COLOR + [r, 0x00, 255 - r, 0xC3])) #BGR format

using literal hex integer notation.

Demo for r = 10:

>>> SET_BG_COLOR = [0xAA, 0x03, 0x03]
>>> r = 10
>>> bytes(SET_BG_COLOR + [r, 0x00, 255 - r, 0xC3])
b'\xaa\x03\x03\n\x00\xf5\xc3'

The hex() function outputs 4 characters per byte; starting with a literal 0x followed by the hex representation of the integer number. Encoded to UTF8 that's still 4 bytes, b'\x30\x78\x30\x31' for the integer value 10, for example, versus b'\x10' for the actual byte you wanted.