您现在的位置是:网站首页> 编程资料编程资料
Python使用struct库的用法小结_python_
2023-05-26
335人已围观
简介 Python使用struct库的用法小结_python_
struct简介
看到struct这么英文单词,大家应该并不陌生,因为c/c++中就有struct,在那里struct叫做结构体。在Python中也使用struct,这充分说明了这个struct应该和c/c++中的struct有很深的渊源。Python正是使用struct模块执行Python值和C结构体之间的转换,从而形成Python字节对象。它使用格式字符串作为底层C结构体的紧凑描述,进而根据这个格式字符串转换成Python值。
准确地讲,Python没有专门处理字节的数据类型。但由于
b'str'可以表示字节,所以,字节数组=二进制str。而在C语言中,我们可以很方便地用struct、union来处理字节,以及字节和int,float的转换。故提供一个库来做转换。
常用函数
struct.pack(format:str, v1, v2, …)
按format的格式打包v1、v2等参数
import struct result = [1,2,3,4,5] print([struct.pack('struct.unpack(format:str,buffer:bytes)
按format的格式解包buffer数据,注意结果是一个数组
import struct result = bytes.fromhex('10002030000000') print(struct.unpack('上代码是按小端序列进行解析的
10被解析成了16
0020被解析成了 0x00 + 0x20 * 256 = 32*256 = 8192
30000000被解析成了 0x30 + 0x0 * 256 + 0x0 * 16³ + 0x0 * 256² = 48
struct.calcsize(format:str)
按format的格式计算这个格式本应该的大小
import struct print(struct.calcsize('B是1个字节,H是2个字节,I是4个字节,共7个字节
format参数的用法
数据
| Format | C Type | Python | 字节数 |
|---|---|---|---|
| x | pad byte | None | 1 |
| c | char | int | 1 |
| b | signed char | int | 1 |
| B | unsigned char | int | 1 |
| ? | Bool | bool | 1 |
| h | short | int | 2 |
| H | unsigned short | int | 2 |
| i | int | int | 4 |
| I | unsigned int | int | 4 |
| l | long | int | 4 |
| L | unsigned long | int | 4 |
| q | long long | int | 8 |
| Q | unsigned long long | int | 8 |
| f | float | float | 4 |
| d | double | float | 8 |
| s | char[] | bytes | 1 |
| p | char[] | bytes | 1 |
| P | void * | int | 0 |
描述符
| Character | Byte order | Size | alignment |
|---|---|---|---|
@ | native | native | 凑足4个字节 |
= | native | standard | 不作变化 |
< | little-endian | standard | 不作变化 |
> | big-endian | standard | 不作变化 |
! | network (= big-endian) | standard | 不作变化 |
到此这篇关于Python使用struct库的用法小结的文章就介绍到这了,更多相关Python使用struct库内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关内容
- python np.arange 步长0.1的问题需要特别注意_python_
- 一个Python优雅的数据分块方法详解_python_
- python目标检测YoloV4当中的Mosaic数据增强方法_python_
- Python零钱兑换的实现代码_python_
- 基于np.arange与np.linspace细微区别(数据溢出问题)_python_
- Python远程SSH库Paramiko详细操作_python_
- python目标检测数据增强的代码参数解读及应用_python_
- python等间距取值方式_python_
- 教你使用Pycharm配置远程Jupyter_python_
- 详解Python中迭代器和生成器的原理与使用_python_
