How can I use the readinto()
method call to an offset inside a bytearray
, in the same way that struct.unpack_from
works?
In computer science, an offset within an array or other data structure object is an integer indicating the distance (displacement) between the beginning of the object and a given element or point, presumably within the same object.
Python | bytearray() function bytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256.
The bytearray type is a mutable sequence of integers in the range between 0 and 255. It allows you to work directly with binary data. It can be used to work with low-level data such as that inside of images or arriving directly from the network. Bytearray type inherits methods from both list and str types.
The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With