我正在尝试转换以下 perl 代码:
unpack(.., "Z*")
对于 python,但是 struct.unpack() 中缺少“*”格式修饰符似乎使这不可能。有没有办法在python中做到这一点?
PS perldoc 中 perl 中的“*”修饰符 - 为重复计数提供 * 而不是数字意味着使用剩余的项目,...
因此,虽然 python 有像 perl 这样的数字重复计数,但它似乎缺少 * 重复计数。
python的struct.unpack
没有Z
格式
Z A null-terminated (ASCIZ) string, will be null padded.
我认为这
unpack(.., "Z*")
将会:
data.split('\x00')
尽管这会去除空值
我假设您创建了结构数据类型并且您知道结构的大小。如果是这种情况,那么您可以创建一个为该结构分配的缓冲区并将值打包到缓冲区中。解包时,您可以使用相同的缓冲区直接解包,只需指定起点即可。
例如
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)
您必须自己计算重复次数:
n = len(s) / struct.calcsize(your_fmt_string)
f = '%d%s' % (n, your_fmt_string)
data = struct.unpack(s, f)
我假设your_fmt_string
不会解包多个元素,并且len(s)
完全除以该元素的打包大小。