Skip to main content
 首页 » 编程设计

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

2024年10月24日13cloudgamer

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

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