尝试保存字节序时,Python struct.pack() 'struct.error: bad char in struct format' [英] Python struct.pack() 'struct.error: bad char in struct format' when trying to save endianess
问题描述
我正在尝试打包一个字符串和一个字符串的长度.
I am trying to pack a string and the length of a string.
fmt = '<P' + str(len(string)) + 'p'
这导致我出错:struct.error: bad char in struct format而,做
This leads me to an error : struct.error: bad char in struct format Whereas, doing
fmt = 'P' + str(len(string))+'p'
不会给我一个错误.我无法理解为什么会发生这种情况,我的理解是指定 '<'无论本机机器如何,一开始都会使其成为小端.
Does not give me an error. I am unable to understand why this happens, my understanding is that specifying '<' at the start will make it little endian regardless of the native machine.
推荐答案
来自 struct
模块文档字符串:
From the struct
module docstring:
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
格式时你不能修改endianess;它仅以原生格式提供.
So you can't modify the endianess when you use the P
format; it is only available in native format.
另见此处的注释 5:https://docs.python.org/2/library/struct.html#format-characters
这篇关于尝试保存字节序时,Python struct.pack() 'struct.error: bad char in struct format'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!