11

How can I use the readinto() method call to an offset inside a bytearray, in the same way that struct.unpack_from works?

Matt Joiner
  • 112,946
  • 110
  • 377
  • 526

1 Answers1

19

You can use a memoryview to do the job. For example:

dest = bytearray(10) # all zero bytes
v = memoryview(dest)
ioObject.readinto(v[3:])
print(repr(dest))

Assuming that iObject.readinto(...) reads the bytes 1, 2, 3, 4, and 5 then this code prints:

bytearray(b'\x00\x00\x00\x01\x02\x03\x04\x05\x00\x00')

You can also use the memoryview object with struct.unpack_from and struct.pack_into. For example:

dest = bytearray(10) # all zero bytes
v = memoryview(dest)
struct.pack_into("2c", v[3:5], 0, b'\x07', b'\x08')
print(repr(dest))

This code prints

bytearray(b'\x00\x00\x00\x07\x08\x00\x00\x00\x00\x00')
srgerg
  • 18,719
  • 4
  • 57
  • 39