Python: struct.pack_into 和 struct.unpack_from 函数学习

本文介绍了Python中的struct.pack_into和struct.unpack_from函数,用于处理自定义协议的打包和解包。这两个函数允许在缓冲区的特定偏移位置进行操作,适合接口测试中涉及二进制数据的场景。通过示例和应用场景阐述了它们在自定义协议接口测试中的重要作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、 函数定义

 

struct.pack_into(fmt, buffer, offset, v1, v2, ...)

Pack the values v1, v2, ... according to the format string fmt and write the packed bytes into the writable buffer buffer starting at position offset. Note that offset is a required argument.

按照指定的格式fmt,将v1,v2...打包到buffer中,其中偏移位置为offset

 

struct.unpack_from(fmt, buffer, offset=0)

Unpack from buffer starting at position offset, according to the format string fmt. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes, minus offset, must be at least the size required by the format, as reflected by calcsize().

按照指定的格式fmt,从偏移位置offset开始解包,返回数据格式是一个元组(v1,v2...)

 

二、简单的脚本示例

 

from ctypes import create_string_buffer
import struct
import binascii

#创建了一个7个字节长度的buffe
`struct` 模块在 Python 中用于处理结构化数据,特别是二进制数据的读写操作。你可以使用这个模块来定义数据的结构,然后根据这些结构从文件或内存中读取写入数据。 如果你想用 `struct` 读写包含“王涛机械11128”这样的文本字符串的二进制文件,通常情况下,你会先将字符串转换为字节序列(如果尚未这样做),因为 `struct` 需要直接处理二进制数据。这里假设你有一个名为 "filename.txt" 的文件,你可以按照以下步骤进行: ```python import struct # 假设原始文本存储在 'data' 变量中 data = '王涛机械11128' # 将文本转换为字节串 (UTF-8编码) byte_data = data.encode('utf-8') # 定义结构体格式,这里我们简单地使用固定大小的字符数组 format_code = '8s' # 's' 表示字符串,'8' 表示长度为8个字符(包括终止符) # 写入文件 with open("output.bin", "wb") as file: struct.pack_into(format_code, file, 0, byte_data) # 读取文件 with open("output.bin", "rb") as file: # 使用pack函数从文件读取并解析数据 read_bytes = file.read(struct.calcsize(format_code)) read_str = struct.unpack_from(format_code, read_bytes)[0].decode('utf-8') print(f"Read from file: {read_str}") ``` 这段代码首先将文本转换成字节串,然后使用 `struct.pack_into` 将其写入文件,接着用 `struct.unpack_from` 来从文件中读回数据。请注意,如果你的文本可能有不同长度,上述格式可能需要修改,例如使用变长字符串 (`'{length}s'`) 或者计算实际字符串长度的方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值