0

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.

4
  • 1
    You should try using io.BytesIO if you want to append into some buffer Commented Aug 10, 2021 at 17:15
  • theirs another issue with your code, you recive a IndexError: index out of range Commented Aug 10, 2021 at 17:17
  • @ClownDown when replaced to b'' : TypeError: can't concat int to bytes Commented Aug 10, 2021 at 17:17
  • data_bs is a string, c is bytes, c[i] is a byte, you have the types mixed up. Commented Aug 10, 2021 at 17:17

3 Answers 3

2

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'
Sign up to request clarification or add additional context in comments.

Comments

0

It's unclear what you're trying to concatenate them into from the question. However, if you want to create a string like data_bs implies you can do this:

for i in c:
    data_bs += str(i)
print(data_bs)

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.