开发者

python struct unpack

开发者_运维百科

I'm trying to convert the following perl code:

unpack(.., "Z*")

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

P.S. The "*" modifier in perl from the perldoc - Supplying a * for the repeat count instead of a number means to use however many items are left, ...

So although python has a numeric repeat count like perl, it seems to lack a * repeat count.


python's struct.unpack doesn't have the Z format

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

i think this

unpack(.., "Z*")

would be:

data.split('\x00')

although that strips the nulls


I am assuming that you create the struct datatype and you know the size of the struct. If that is the case, then you can create a buffer allocated for that struct and the pack the value into the buffer. While unpacking, you can use the same buffer to unpack directly by just specifying the starting point.

For e.g.

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)


You must calculate the repeat count yourself:

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

I am assuming your_fmt_string doesn't unpack more than one element, and len(s) is perfectly divided by that element's packed size.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜