考虑以下代码:
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/