Read in bytearray for offset?

How can I use the readinto() method call to offset inside a bytearray , just like struct.unpack_from works?

+6
source share
1 answer

You can use memoryview to do the job. For instance:

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

Assuming iObject.readinto(...) reads 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 a memoryview object with struct.unpack_from and struct.pack_into . For instance:

 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') 
+12
source

Source: https://habr.com/ru/post/902347/


All Articles