【问题标题】:Python struct.pack() 'struct.error: bad char in struct format' when trying to save endianess尝试保存字节序时,Python struct.pack() 'struct.error: bad char in struct format'
【发布时间】:2015-10-06 02:41:11
【问题描述】:

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

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

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

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

不会给我一个错误。我无法理解为什么会发生这种情况,我的理解是在开始时指定'

【问题讨论】:

    标签: python struct


    【解决方案1】:

    来自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

    【讨论】:

    • 在文档中错过了这个:(。我想我会使用 long long 而不是指针,我只是想要一个大的无符号整数来指定我的字符串长度。
    【解决方案2】:

    "the struct module documentation 看到该表。

    正如 Warren Weckesser 所指出的,P 格式不能修改其字节顺序,但如果您使用“

    【讨论】:

      猜你喜欢
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 2023-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      相关资源
      最近更新 更多