解压缩以ASCIIZ字符串结尾的结构

时间:2012-08-07 17:19:26

标签: python struct

我正在尝试使用struct.unpack()拆分以ASCII字符串结尾的数据记录。

记录(恰好是TomTom ov2记录)具有这种格式(存储的小端):

  • 1个字节
  • 总记录大小的4字节int(包括此字段)
  • 4字节int
  • 4字节int
  • 变长字符串,以null结尾

unpack()要求字符串的长度包含在您传递的格式中。我可以使用第二个字段和记录其余部分的已知大小--13个字节 - 来获取字符串长度:

str_len = struct.unpack("<xi", record[:5])[0] - 13
fmt = "<biii{0}s".format(str_len)

然后继续完全解包,但由于该字符串是空终止的,我真的希望unpack()能为我做这件事。如果我遇到一个不包含自己大小的结构,我也很高兴。

我怎样才能实现这一目标?

2 个答案:

答案 0 :(得分:7)

我制作了两个新功能,可用作标准包和解包功能的直接替换。它们都支持'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 ('<izizi', 1, 'Hello', 2, ' world!', 3)
>>> print line.encode('hex')
0100000048656c6c6f000200000020776f726c64210003000000
>>> print unpack ('<izizi',line)
(1, 'Hello', 2, ' world!', 3)
>>>

答案 1 :(得分:5)

实际上,无大小记录非常容易处理,因为struct.calcsize()会告诉您它所期望的长度。您可以使用该数据和实际的数据长度来构造包含正确字符串长度的unpack()的新格式字符串。

这个函数只是unpack()的包装器,允许最后一个位置的新格式字符将丢弃终端NUL:

import struct
def unpack_with_final_asciiz(fmt, dat):
    """
    Unpack binary data, handling a null-terminated string at the end 
    (and only at the end) automatically.

    The first argument, fmt, is a struct.unpack() format string with the 
    following modfications:
    If fmt's last character is 'z', the returned string will drop the NUL.
    If it is 's' with no length, the string including NUL will be returned.
    If it is 's' with a length, behavior is identical to normal unpack().
    """
    # Just pass on if no special behavior is required
    if fmt[-1] not in ('z', 's') or (fmt[-1] == 's' and fmt[-2].isdigit()):
        return struct.unpack(fmt, dat)

    # Use format string to get size of contained string and rest of record
    non_str_len = struct.calcsize(fmt[:-1])
    str_len = len(dat) - non_str_len

    # Set up new format string
    # If passed 'z', treat terminating NUL as a "pad byte"
    if fmt[-1] == 'z':
        str_fmt = "{0}sx".format(str_len - 1)
    else:
        str_fmt = "{0}s".format(str_len)
    new_fmt = fmt[:-1] + str_fmt

    return struct.unpack(new_fmt, dat)

>>> dat = b'\x02\x1e\x00\x00\x00z\x8eJ\x00\xb1\x7f\x03\x00Down by the river\x00'
>>> unpack_with_final_asciiz("<biiiz", dat)
(2, 30, 4886138, 229297, b'Down by the river')
相关问题