Unpack python

I am trying to convert the following perl code:

unpack(.., "Z*") 

in python, however, the lack of a "*" format modifier in struct.unpack () seems impossible. Is there a way I can do this in python?

PS The modifier "*" in perl from perldoc. Delivering a * for a retry counter instead of a number means using, however, many elements remain, ...

So, although python has a numerical number of repetitions, such as perl, it seems that there is no repetition counter.

+1
source share
3 answers

python struct.unpack doesn't have Z format

 ZA null-terminated (ASCIZ) string, will be null padded. 

I think that it is

 unpack(.., "Z*") 

:

 data.split('\x00') 

although it's strbs nulls

+3
source

I assume that you are creating a struct data type and know the size of the structure. If so, then you can create a buffer allocated for this structure, and a packet - a value in the buffer. When unpacking, you can use the same buffer to unpack directly, just specifying the starting point.

For instance,

 import ctypes import struct s = struct.Struct('I') b = ctypes.create_string_buffer(s.size) s.pack_into(b, 0, 42) s.unpack_from(b, 0) 
+2
source

You must calculate the number of repetitions yourself:

 n = len(s) / struct.calcsize(your_fmt_string) f = '%d%s' % (n, your_fmt_string) data = struct.unpack(s, f) 

I assume that your_fmt_string does not decompress more than one element, and len(s) perfectly divided by this size of the packed element.

0
source

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


All Articles