how concatenate bytes eg. sample code:
data_bs = ''
c = b'\x00\x00\xa0\xe1\x00'
for i in list(range(0, len(c), 2)):
data_bs += c[i+1] + c[i]
Error code:
TypeError: can only concatenate str (not "int") to str
Im want fix byte order.
Indexing into bytes directly gives an int, so the easiest solution here is to just make data_bs into bytes and use slices:
In [132]: data_bs = b''
...: c = b'\x00\x00\xa0\xe1\x00'
...:
...: for i in list(range(0, len(c), 2)):
...: data_bs += c[i+1:i+2] + c[i:i+1]
...:
In [133]: data_bs
Out[133]: b'\x00\x00\xe1\xa0\x00'
For best performance, preallocate the output array and then copy bytes in the order you require e.g.
a = b'\x00\x01\x02\x03'
b = bytearray(len(a))
for cnt in range(0, int(len(a) / 2)):
b[cnt * 2] = a[cnt * 2 + 1]
b[cnt * 2 + 1] = a[cnt * 2]
print(a)
print(b)
consider what to do if the length is odd e.g.
if len(a) % 2 == 1:
b[len(a) - 1] = a[len(a) - 1]
io.BytesIOif you want to append into some bufferIndexError: index out of range