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?
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')