Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read into a bytearray at an offset?

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

like image 764
Matt Joiner Avatar asked Nov 25 '11 00:11

Matt Joiner


People also ask

What is offset in byte array?

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.

What does Bytearray mean in Python?

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.

What is type Bytearray?

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.

What is the difference between bytes and Bytearray?

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.


1 Answers

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')
like image 189
srgerg Avatar answered Oct 06 '22 00:10

srgerg