python - struct.pack(f'{len(x)}s', x) 有什么作用吗?

标签 python c struct struct.pack

考虑以下代码:

import struct

x = b'example' # can be any bytes object
y = struct.pack(f'{len(x)}s', x)
print(x == y)

如果我明白the documentation正确地,该函数调用将返回具有 len(x) 数组的结构的二进制表示形式。 char s (包含 x 的内容)作为其唯一成员。有没有什么情况下这不仅仅是x本身?

或者,将这个问题改写为 C 视角(因为我也标记了这个问题),C 标准是否允许 struct MyStruct { char s[MY_SIZE]; }; 的多个二进制表示? ?

我问这个是因为 Mozilla指示我这样做(Ctrl + F 代表“Python 3”):

# Encode a message for transmission, given its content.
def encode_message(message_content):
    encoded_content = json.dumps(message_content).encode("utf-8")
    encoded_length = struct.pack('=I', len(encoded_content))
    #  use struct.pack("10s", bytes), to pack a string of the length of 10 characters
    return {'length': encoded_length, 'content': struct.pack(str(len(encoded_content))+"s",encoded_content)}

最佳答案

这完全没有意义。编写该示例的人可能没有仔细考虑或者不太理解 struct.pack 的作用。

特别是,即使你有一个完全奇怪的平台,它实际上会填充 struct MyStruct { char s[MY_SIZE]; };,Python struct 模块仍然不会填充 struct.pack 调用。 struct.pack 不添加尾部填充(或前导填充,如果您有一些真的奇怪的平台可以这样做)。引用 docs :

Padding is only automatically added between successive structure members. No padding is added at the beginning or the end of the encoded struct.

关于python - struct.pack(f'{len(x)}s', x) 有什么作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73102613/

相关文章:

python - 子图中的 ConciseDateFormatter

c - 使用 Xcode 在 Mac 上的 C 中 fputs 崩溃

c - 如何即时创建变量名称

python - 保留一个元素的快速计算均值

python - 使用 scikit-image 将 numpy 数组保存为高精度(16 位)图像

python - JSONSchema 暗示其架构的资源

c - 如何将文本文件复制到C中的字符串?

c - 如何防止在源代码中调用某些api?

c - 将数据存储在头文件中包含数组的 Stucts 中

c - 在 Struct 中索引指向 char 指针的指针会覆盖所有值吗?