1 回答
TA贡献1830条经验 获得超9个赞
您需要将字符串的长度添加到格式字符串中:
packed = pack("i4s", 1, "john")
unpacked = unpack("i4s", packed)
print(unpacked[1])
>> john
如果您需要一个可变长度的字符串 - >使用python中的struct模块打包和解包可变长度数组/字符串
编辑:
您的解决方案可以像这样扩展:
from struct import *
def make_struct(user_id, first_name):
first_name_length = len(first_name)
fmt = "ii{}s".format(first_name_length) #generate format string with length of first_name
return pack(fmt, user_id, first_name_length, first_name) #add the length to the pack
def deconstruct_struct(structure):
user_id, first_name_length = unpack("ii", structure[:8]) #extract only userid and length from the pack
fmt = "ii{}s".format(first_name_length) #generate the format string like above
#return unpack(fmt, structure) #this would return a (user_id, length of first name, first_name) tuple
return (user_id, unpack(fmt, structure)[2]) #this way, we return only the (user_id, first_name) tuple
packed = make_struct(1, "john")
unpacked = deconstruct_struct(packed)
- 1 回答
- 0 关注
- 171 浏览
添加回答
举报