1

I am trying to copy a blob of data (some bytes) into a larger block at some position. I can do this easily enough in C, but now I am doing it in Python and I am curious as to what is the best/correct way to do this.

The way I did it was:

struct.pack_into("p", buffer, pos, str(data))

Where data and buffer are of type bytearray. Python would not let me copy the data into the buffer without converting it to a string (see the type conversion above), so I was wondering what is the correct way to insert one bytearray into another?

1 Answer 1

4

bytearray objects are mutable sequences, you can copy the contents of one into another at a given position by assigning to a slice:

buffer[pos:pos + len(data)] = data

There is no need or use for struct.pack_into() here. Note that data can be any iterable of integers, provided they fall in the range 0-255; it doesn't have to be a bytes or bytearray object.

Demo:

>>> buffer = bytearray(10)
>>> data = bytes.fromhex('deadbeef')
>>> pos = 3
>>> buffer[pos:pos + len(data)] = data
>>> buffer
bytearray(b'\x00\x00\x00\xde\xad\xbe\xef\x00\x00\x00')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Good answer - The slice of bytearray buffer from pos to pos + len(data) is replaced by the contents of the iterable bytearray data.

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.