When/why 我应该使用 python 中的结构库来打包和解包吗?

When/why should I use struct library in python to pack and unpack?

我不明白什么时候应该在 python 的结构库中使用 pack 和 unpack 函数? 我也无法理解如何使用它们? 看了之后,我的理解是它们是用来将数据转换成二进制的。然而,当我 运行 一些例子时:

>>> struct.pack("i",34)
'"\x00\x00\x00'

我无法理解它。 我想了解它的目的,这些转换是如何发生的,'\x' 和其他符号是什么 represent/mean 以及解包是如何工作的。

I cant understand when should I use pack and unpack functions in struct library in python?

那么你可能没有理由使用它们。

其他人处理具有低级二进制打包的网络和文件格式,其中 struct 可能非常有用。

However when I run some examples like:

>>> struct.pack("i",34)
'"\x00\x00\x00'

I cant make any sense out of it.

\x 符号用于使用 hexadecimal 表示 bytes 对象的各个字节。 \x00 表示字节值为 0,\x02 表示字节值为 2,\x10 表示字节值为 16,等等。" 是字节 34,所以我们在这个字符串视图中看到 " 而不是 \x22,但是 '\x22\x00\x00\x00''"\x00\x00\x00' 是相同的字符串

http://www.swarthmore.edu/NatSci/echeeve1/Ref/BinaryMath/NumSys.html 可能会帮助您了解一些背景知识,如果这是您需要理解数字的水平。