6

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

记录(它恰好是 TomTom ov2 记录)具有以下格式(存储小端序):

  • 1 个字节
  • 总记录大小为 4 字节 int(包括此字段)
  • 4字节整数
  • 4字节整数
  • 可变长度字符串,以空字符结尾

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

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

然后继续进行完整的解包,但由于字符串是空终止的,我真的希望unpack()能为我做这件事。如果我遇到一个不包括其自身大小的结构,那么拥有它也很好。

我怎样才能做到这一点?

4

2 回答 2

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)
>>>
于 2013-06-14T23:15:35.800 回答
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')
于 2012-08-07T17:19:25.833 回答