如何在python中对32位整数进行字节交换?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27506474/
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
How to byte-swap a 32-bit integer in python?
提问by Patrick B.
Take this example:
拿这个例子:
i = 0x12345678
print("{:08x}".format(i))
# shows 12345678
i = swap32(i)
print("{:08x}".format(i))
# should print 78563412
What would be the swap32-function()
? Is there a way to byte-swap an int
in python, ideally with built-in tools?
会是什么swap32-function()
?有没有办法int
在 python 中进行字节交换,最好是使用内置工具?
采纳答案by Carsten
One method is to use the struct
module:
一种方法是使用struct
模块:
def swap32(i):
return struct.unpack("<I", struct.pack(">I", i))[0]
First you pack your integer into a binary format using one endianness, then you unpack it using the other (it doesn't even matter which combination you use, since all you want to do is swap endianness).
首先,您使用一种字节序将整数打包成二进制格式,然后使用另一种将其解包(使用哪种组合并不重要,因为您要做的只是交换字节序)。
回答by nos
Big endian means the layout of a 32 bit int has the most significant byte first,
大端意味着 32 位 int 的布局首先具有最高有效字节,
e.g. 0x12345678 has the memory layout
例如 0x12345678 具有内存布局
msb lsb
+------------------+
| 12 | 34 | 56 | 78|
+------------------+
while on little endian, the memory layout is
而在小端,内存布局是
lsb msb
+------------------+
| 78 | 56 | 34 | 12|
+------------------+
So you can just convert between them with some bit masking and shifting:
因此,您可以通过一些位掩码和移位在它们之间进行转换:
def swap32(x):
return (((x << 24) & 0xFF000000) |
((x << 8) & 0x00FF0000) |
((x >> 8) & 0x0000FF00) |
((x >> 24) & 0x000000FF))
回答by Artem Zankovich
From python 3.2 you can define function swap32() as the following:
从 python 3.2 你可以定义函数 swap32() 如下:
def swap32(x):
return int.from_bytes(x.to_bytes(4, byteorder='little'), byteorder='big', signed=False)
It uses array of bytes to represent the value and reverses order of bytes by changing endianness during conversion back to integer.
它使用字节数组来表示值并通过在转换回整数期间更改字节顺序来反转字节顺序。