python 内置模块struct的使用
1.模块导入 pack与unpack函数使用
import struct
pack_data = struct.pack('>?hf', False, 30, 68.5)
unpack_data = struct.unpack('>hf', pack_data)
print(pack_data)
print(unpack_data)
1.1 pack(format, v1, v2, …) -> bytes
format: 指定压缩格式,由v1, v2, …决定
v1, v2, … 要压缩的数据
返回: bytes, 压缩后的C语言格式的字节串
1.2 unpack(format, pack_data) ->tuple
format: 按何种格式解压缩
pack_data: 经pack处理后的字节数据
返回: 解压缩后的数据,数据由format确定
2 format
2.1 一般格式
‘字节序|数据类型|数据类…’
2.1.1 字节序
符号 | 说明 |
---|---|
@ | 自动,由CPU架构决定 |
= | 同上 |
< | 小端序 |
> | 大端序 |
! | 和 > 一样 |
2.1.2 数据类型
符号 | C类型 | Python类型 | 说明 |
---|---|---|---|
x | byte | byte | 相当于留空一个字节,用来作字节对齐 |
c | char | string | — |
b | signed byte | int | -127~127 |
B | byte | byte | unsigned byte |
? | bool | _Bool | 0?1 |
h | short | int | — |
H | unsigned short | int | — |
i | int | int | — |
I | unsigned int | int | — |
l | long | int | — |
L | unsigned long | int | — |
f | float | float | — |
d | double | double | — |
s | string | string | 字符串 |
q | long long | int | — |
Q | unsigned long long | int | — |