Python 3 Building an array of bytes Python 3 Building an array of bytes arrays arrays

Python 3 Building an array of bytes


Use a bytearray:

>>> frame = bytearray()>>> frame.append(0xA2)>>> frame.append(0x01)>>> frame.append(0x02)>>> frame.append(0x03)>>> frame.append(0x04)>>> framebytearray(b'\xa2\x01\x02\x03\x04')

or, using your code but fixing the errors:

frame = b""frame += b'\xA2' frame += b'\x01' frame += b'\x02' frame += b'\x03'frame += b'\x04'


what about simply constructing your frame from a standard list ?

frame = bytes([0xA2,0x01,0x02,0x03,0x04])

the bytes() constructor can build a byte frame from an iterable containing int values. an iterable is anything which implements the iterator protocol: an list, an iterator, an iterable object like what is returned by range()...


frame = b'\xa2\x01\x02\x03\x04'

wasn't mentionned till now...