将字节串解读为打包的二进制数据
Posted yuanjiangw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将字节串解读为打包的二进制数据相关的知识,希望对你有一定的参考价值。
struct --- 将字节串解读为打包的二进制数据 — Python 3.8.3 文档 https://docs.python.org/zh-cn/3.8/library/struct.html
源代码: Lib/struct.py
此模块可以执行 Python 值和以 Python bytes
对象表示的 C 结构之间的转换。 这可以被用来处理存储在文件中或是从网络连接等其他来源获取的二进制数据。 它使用 格式字符串 作为 C 结构布局的精简描述以及与 Python 值的双向转换。
注解
默认情况下,打包给定 C 结构的结果会包含填充字节以使得所涉及的 C 类型保持正确的对齐;类似地,对齐在解包时也会被纳入考虑。 选择此种行为的目的是使得被打包结构的字节能与相应 C 结构在内存中的布局完全一致。 要处理平台独立的数据格式或省略隐式的填充字节,请使用 standard
大小和对齐而不是 native
大小和对齐:详情参见 字节顺序,大小和对齐方式。
某些 struct
的函数(以及 Struct
的方法)接受一个 buffer 参数。 这将指向实现了 缓冲协议 并提供只读或是可读写缓冲的对象。 用于此目的的最常见类型为 bytes
和 bytearray
,但许多其他可被视为字节数组的类型也实现了缓冲协议,因此它们无需额外从 bytes
对象复制即可被读取或填充。
struct — Interpret bytes as packed binary data — Python 3.8.3 documentation https://docs.python.org/3.8/library/struct.html
struct
— Interpret bytes as packed binary data
Source code: Lib/struct.py
This module performs conversions between Python values and C structs represented as Python bytes
objects. This can be used in handling binary data stored in files or from network connections, among other sources. It uses Format Strings as compact descriptions of the layout of the C structs and the intended conversion to/from Python values.
Note
By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard
size and alignment instead of native
size and alignment: see Byte Order, Size, and Alignment for details.
Several struct
functions (and methods of Struct
) take a buffer argument. This refers to objects that implement the Buffer Protocol and provide either a readable or read-writable buffer. The most common types used for that purpose are bytes
and bytearray
, but many other types that can be viewed as an array of bytes implement the buffer protocol, so that they can be read/filled without additional copying from a bytes
object.
以上是关于将字节串解读为打包的二进制数据的主要内容,如果未能解决你的问题,请参考以下文章
stm32串口自定义协议接收一串十六进制数据(将其中两个字节转化为十进制数据)+部分串口基础知识
如何将一串二进制数转换为 C 中的字符(每个字符都必须有一个半字节)?