The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor

--

Chapters
00:00 Python 3 - On Converting From Ints To 'Bytes' And Then Concatenating Them (For Serial Transm
02:01 Accepted Answer Score 7
02:58 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.