python中的解包函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17627388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
unpack function in python
提问by Neon Flash
I am trying to understand the unpack function in Python and how it uses the format string.
我试图了解 Python 中的解包函数以及它如何使用格式字符串。
I am using the format string, "I" which corresponds to unsigned int (size, 4 bytes) as an example.
我使用格式字符串“I”作为示例,它对应于 unsigned int(大小,4 个字节)。
As per the documentation, the unpack function will accept a string and convert it to a list of values based on the format string.
根据文档,解包函数将接受一个字符串并将其转换为基于格式字符串的值列表。
http://docs.python.org/2/library/struct.html
http://docs.python.org/2/library/struct.html
So, I used the input value as a string, "test" and here is the output:
因此,我将输入值用作字符串“test”,这是输出:
>>> import struct
>>> input="test"
>>> l = struct.unpack("I", input)[0]
>>> print l
1953719668
I am trying to understand how the output value was derived from the input.
我试图了解输出值是如何从输入中导出的。
>>> from struct import *
>>> calcsize('I')
4
size of 'I' is 4 bytes. the string, "test" has 4 characters which is 4 bytes. I tried converting each character to its corresponding Hex ASCII value and storing it in little endian order but it does not match the output above.
'I' 的大小是 4 个字节。字符串“test”有 4 个字符,即 4 个字节。我尝试将每个字符转换为其相应的十六进制 ASCII 值并以小端顺序存储它,但它与上面的输出不匹配。
Any help would be appreciated.
任何帮助,将不胜感激。
采纳答案by falsetru
Use 4s
if you want unpack string as is.
4s
如果您想按原样解压缩字符串,请使用。
>>> struct.unpack('4s', 'test')[0]
'test'
1953719668 is derived by: (little endian)
1953719668 衍生自:(小端)
>>> ord('t') + (ord('e') << 8) + (ord('s') << 16) + (ord('t') << 24)
1953719668