❌ ✅ ✅ ✅ ✅ ✅ ✅

ustruct(二进制打包) – Pack and unpack binary data

此模块提供在 Python 值与类 C 数据结构之间转换的函数。

calcsize(format: str) → int

获取格式字符串对应的数据大小

参数:

format (str) – 数据格式字符串。

返回:

表示此格式所需的字节数。

pack(format, value1, value2, ...)

使用给定格式打包值。

参数:

format (str) – 数据格式字符串。

返回:

编码为字节的数据。

pack_into(format, buffer, offset, value1, value2, ...)

使用给定格式编码值并将其写入给定缓冲区。

参数:
  • format (str) – 数据格式字符串。

  • buffer (bytearray) – 用于存储编码数据的缓冲区。

  • offset (int) – 距缓冲区起始处的偏移量。使用负值表示从缓冲区末尾开始计数。

unpack(format, data) → tuple

使用给定格式解码二进制数据。

参数:
  • format (str) – 数据格式字符串。

  • data (bytes or bytearray) – 要解包的数据。

返回:

解码后的数据,为值的元组。

unpack_from(format, data, offset) → tuple

使用给定格式从缓冲区解码二进制数据。

参数:
  • format (str) – 数据格式字符串。

  • data (bytes or bytearray) – 要解包的数据缓冲区。

  • offset (int) – 距数据起始处的偏移量。使用负值表示从数据末尾开始计数。

返回:

解码后的数据,为值的元组。

支持以下字节序:

字符

字节序

大小

对齐方式

@

本机

本机

本机

<

小端序

标准

无

>

大端序

标准

无

!

网络序(= 大端序)

标准

无

支持以下数据类型:

格式

C 类型

Python 类型

标准大小

b

有符号字符 (signed char)

整数

1

B

无符号字符 (unsigned char)

整数

1

h

短整型 (short)

整数

2

H

无符号短整型 (unsigned short)

整数

2

i

int

整数

4

I

无符号整型 (unsigned int)

整数

4

l

长整型 (long)

整数 (1)

4

L

无符号长整型 (unsigned long)

整数 (1)

4

q

长长整型 (long long)

整数 (1)

8

Q

无符号长长整型 (unsigned long long)

整数 (1)

8

f

float

float

4

d

双精度浮点型 (double)

float

8

s

字符数组 (char[])

bytes

P

空指针 (void *)

整数

  • (1) 支持最大 +/-1073741823 的值