python - 将 struct.pack 与字符串一起使用

标签 python struct

我正在尝试使用 struct.pack,以便可以将字符串写入文件中。当我这样做时,我收到以下错误:

File "----", line 166, in main
struct.pack('>256s', *master_header)
struct.error: pack expected 1 items for packing (got 256)

现在,阅读 here我好像用对了。我指定在字符串中获取 256 个字节/字符。

我使用的是3.3.3版本。

最佳答案

documentation说:

For the 's' format character, the count is interpreted as the size of the string, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' means 10 characters.

因此,>256s 需要一个 256 字节长的字符串。如果 master_header 已经是这样的字符串,只需将其传递给 struct.pack 而不带 *

在调用站点使用 * 会导致字符串本身被解包为其组成字符,字符串是可迭代的。因此,struct.pack 接收其 256 个单独字符作为参数,从而导致观察到的错误。

关于python - 将 struct.pack 与字符串一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21726324/

相关文章:

结构编译器错误 vector 的 C++ 迭代器

c++ - 具有常量成员的结构体的默认复制操作

c - 遍历结构数组

php - PHP中可以嵌入Python吗?

python - 为什么 SymPy 不简化表达式?

python - 如何解释 mp3/wav 文件的 matplotlib 图中的各种颜色

c - C 中的结构体定义

c++ - 转换指针以重用缓冲区

python - PyMongo 统计

python - 如何使用 cx_freeze 卡住一些 python 测试?