包装和使用Python中结构模块拆包变长数组/串 [英] packing and unpacking variable length array/string using the struct module in python
问题描述
我试图绕过一个包装的抓地力和在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:
如果我有一个可变长度textstring,想打包并以最优雅的方式解压呢?
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?
推荐答案
的结构
模块只支持固定长度的结构。对于变长字符串,你的选项是:
The struct
module does only support fixed-length structures. For variable-length strings, your options are either:
-
动态构建您的格式字符串(
STR
将要转换为字节
才通过它包()
)
s = bytes(s, 'utf-8') # Or other appropriate encoding
struct.pack("I%ds" % (len(s),), len(s), s)
跳过结构
,只使用普通的字符串的方法来将字符串添加到您的包()
- 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中结构模块拆包变长数组/串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!