尝试保存字节顺序时的 Python struct.pack() 'struct.error: bad char in struct format'

标签 python struct

我正在尝试打包一个字符串和一个字符串的长度。

fmt = '<P' + str(len(string)) + 'p'

这导致我出错:struct.error: bad char in struct format 然而,做

fmt = 'P' + str(len(string))+'p'

不给我一个错误。我无法理解为什么会发生这种情况,我的理解是在开头指定“<”将使它成为小端,而不管 native 是什么。

最佳答案

来自 struct 模块文档字符串:

The remaining chars indicate types of args and must match exactly;
...
Special case (only available in native format):
  P:an integer type that is wide enough to hold a pointer.

所以在使用P格式时不能修改字节顺序;它仅以原生格式提供。

另见注释 5:https://docs.python.org/2/library/struct.html#format-characters

关于尝试保存字节顺序时的 Python struct.pack() 'struct.error: bad char in struct format',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32960877/

相关文章:

c++ - 为什么当我从文件加载它的序列化时,我的充满结构的 vector 的大小如此之大?

c# - 如何将 byte[] 转换为 struct(包含一个 byte[] 成员和 length 成员)

python - Python 中的 JSON.loads() ValueError 额外数据

python - Numba jit : "Typing error" and "All templates rejected with/without literals" 问题

python - np.logical_and 三个测试

python - 使用 Python 将 Oracle 数据库表导出为 XML 文件?

python - 使用 Darts 进行多协变量时间序列预测

将数组的变量复制到另一个数组,该数组是带有字符的结构

c - 链表代码中的插入操作不起作用

c - 任何类型的一般排序,与结构作斗争