使用python中的struct模块打包和解包可变长度数组/字符串 [英] packing and unpacking variable length array/string using the struct module in python

查看:21
本文介绍了使用python中的struct模块打包和解包可变长度数组/字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试掌握 Python 3 中二进制数据的打包和解包.它实际上并不难理解,除了一个问题:

I am trying to get a grip around the packing and unpacking of binary data in Python 3. Its actually not that hard to understand, except one problem:

如果我有一个可变长度的文本字符串并且想以最优雅的方式打包和解包怎么办?

what if I have a variable length textstring and want to pack and unpack this in the most elegant manner?

据我所知,我只能直接解压缩固定大小的字符串?在这种情况下,有没有什么优雅的方法可以绕过这个限制而不填充大量不必要的零?

As far as I can tell from the manual I can only unpack fixed size strings directly? In that case, are there any elegant way of getting around this limitation without padding lots and lots of unnecessary zeroes?

推荐答案

struct 模块只支持固定长度的结构.对于可变长度的字符串,您的选择是:

The struct module does only support fixed-length structures. For variable-length strings, your options are either:

  • 动态构造您的格式字符串(str 必须先转换为 bytes,然后再将其传递给 pack()):

  • Dynamically construct your format string (a str will have to be converted to a bytes before passing it to pack()):

s = bytes(s, 'utf-8')    # Or other appropriate encoding
struct.pack("I%ds" % (len(s),), len(s), s)

  • 跳过 struct 并使用普通的字符串方法将字符串添加到您的 pack()-ed 输出: struct.pack("I", len(s)) + s

  • Skip struct and just use normal string methods to add the string to your pack()-ed output: struct.pack("I", len(s)) + s

    要拆包,您只需一次拆包:

    For unpacking, you just have to unpack a bit at a time:

    (i,), data = struct.unpack("I", data[:4]), data[4:]
    s, data = data[:i], data[i:]
    

    如果你做了很多这样的事情,你总是可以添加一个帮助函数,它使用 calcsize 来进行字符串切片:

    If you're doing a lot of this, you can always add a helper function which uses calcsize to do the string slicing:

    def unpack_helper(fmt, data):
        size = struct.calcsize(fmt)
        return struct.unpack(fmt, data[:size]), data[size:]
    

    这篇关于使用python中的struct模块打包和解包可变长度数组/字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆