在python中使用结构包
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18718709/
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
Using struct pack in python
提问by user2578666
I have a number in integer form which I need to convert into 4 bytes and store it in a list . I am trying to use the struct module in python but am unable to get it to work:
我有一个整数形式的数字,我需要将其转换为 4 个字节并将其存储在列表中。我正在尝试在 python 中使用 struct 模块,但无法让它工作:
struct.pack("i",34);
This returns 0 when I am expecting the binary equivalent to be printed. Expected Output:
当我期望打印等效的二进制文件时,这将返回 0。预期输出:
[0x00 0x00 0x00 0x22]
But struct.pack is returning empty. What am I doing wrong?
但是 struct.pack 返回空。我究竟做错了什么?
采纳答案by Martijn Pieters
The output is returned as a byte string, and Python will print such strings as ASCII characters whenever possible:
输出作为字节字符串返回,Python 会尽可能将此类字符串打印为 ASCII 字符:
>>> import struct
>>> struct.pack("i",34)
'"\x00\x00\x00'
Note the quote at the start, that's ASCII codepoint 34:
请注意开头的引号,即 ASCII 代码点 34:
>>> ord('"')
34
>>> hex(ord('"'))
'0x22'
If you expected the ordering to be reversed, then you may need to indicate a byte order:
如果您希望顺序颠倒,那么您可能需要指明字节顺序:
>>> struct.pack(">i",34)
'\x00\x00\x00"'
where >
indicates big-endian alignment.
其中>
表示大端对齐。