Python 结构打包、解包

Python struct module能够在 Python 值和 C 结构之间进行转换,这些结构被表示为 Python Strings

Python 结构

  • Python struct 模块可用于处理存储在文件、数据库或网络连接等中的二进制数据
  • 它使用格式字符串作为 C 结构的布局和意图转换到/从 Python 值的紧凑描述

Python 功能结构

struct 模块中有五个重要函数 - pack(), unpack(), calcsize(), pack_into()unpack_from(). 在所有这些函数中,我们必须提供将数据转换为二进制的格式。

1?: boolean
2h: short
3l: long
4i: int
5f: float
6q: long long int

您可以找到完整的格式字符列表(https://docs.python.org/3.7/library/struct.html#format-characters)。

基于 Python struct.pack( )

此函数将值列表包装到指定类型的 String 表示中. 参数必须准确匹配格式所要求的值。

1import struct
2
3var = struct.pack('hhl', 5, 10, 15)
4print(var)
5
6var = struct.pack('iii', 10, 20, 30)
7print(var)

When we run this script, we get the following representation: python struct pack Note that ‘b’ in the Output stands for binary.

点击查看 Python struct.unpack()

此函数将包装值解包装到其原始表示格式中,该函数总是返回一个 tuple,即使只有一个元素。

1import struct
2var = struct.pack('hhl', 5, 10, 15)
3print(var)
4print(struct.unpack('hhl', var))

When we run this script, we get back our original representation: python struct unpack Clearly, we must tell the Python interpreter the format we need to unpack the values into.

Python 定位( )

此函数计算并返回具有特定格式的 struct 的 String 表示的大小. 大小以字节计算. 让我们快速看看一个示例代码片段:

1import struct
2
3var = struct.pack('hhl', 5, 10, 15)
4print(var)
5print("Size of String representation is {}.".format(struct.calcsize('hhl')))

When we run this script, we get the following representation: python struct calcsize

Python struct pack_into(), unpack_from() 使用

这些函数允许我们将值包装到字符串缓冲器中,然后从字符串缓冲器中卸载。

 1import struct
 2# ctypes is imported to create a string buffer
 3import ctypes
 4
 5# As shown in previous example
 6size = struct.calcsize('hhl')
 7print(size)
 8
 9# Buffer 'buff' is created from ctypes
10buff = ctypes.create_string_buffer(siz)
11
12# struct.pack_into() packs data into buff and it doesn't return any value
13# struct.unpack_from() unpacks data from buff, returns a tuple of values
14print(struct.pack_into('hhl', buff, 0, 5, 10, 15))
15print(struct.unpack_from('hhl', buff, 0))

When we run this script, we get the following representation: Python Struct pack_into and unpack_from string buffer That's all for a short introduction of python struct module.

Published At
Categories with 技术
Tagged with
comments powered by Disqus