我制作了两个新功能,可用作标准包和解包功能的直接替换.它们都支持’z’字符来打包/解包ASCIIZ字符串.格式字符串中’z’字符的出现位置或出现次数没有限制:
import struct
def unpack (format,buffer) :
while True :
pos = format.find ('z')
if pos < 0 :
break
asciiz_start = struct.calcsize (format[:pos])
asciiz_len = buffer[asciiz_start:].find('\0')
format = '%s%dsx%s' % (format[:pos],asciiz_len,format[pos+1:])
return struct.unpack (format,buffer)
def pack (format,*args) :
new_format = ''
arg_number = 0
for c in format :
if c == 'z' :
new_format += '%ds' % (len(args[arg_number])+1)
arg_number += 1
else :
new_format += c
if c in 'cbB?hHiIlLqQfdspP' :
arg_number += 1
return struct.pack (new_format,*args)
以下是如何使用它们的示例:
>>> from struct_z import pack,unpack
>>> line = pack ('
>>> print line.encode('hex')
0100000048656c6c6f000200000020776f726c64210003000000
>>> print unpack ('
(1,3)
>>>