Python 3 - On Converting From Ints To 'bytes' And Then Concatenating Them (for Serial Transmission)
After much fruitless searching... I am having a very specific issue understanding the way 'bytes' and hexadecimal content is handled in Python 3.2. I KNOW I'm misunderstanding, but
Solution 1:
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 inrange(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 inrange(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.
Post a Comment for "Python 3 - On Converting From Ints To 'bytes' And Then Concatenating Them (for Serial Transmission)"