Pat*_* B. 19 python integer endianness
举个例子:
i = 0x12345678
print("{:08x}".format(i))
# shows 12345678
i = swap32(i)
print("{:08x}".format(i))
# should print 78563412
Run Code Online (Sandbox Code Playgroud)
会是什么swap32-function()?有没有办法int在python中进行字节交换,理想情况下使用内置工具?
Car*_*ten 25
一种方法是使用该struct模块:
def swap32(i):
return struct.unpack("<I", struct.pack(">I", i))[0]
Run Code Online (Sandbox Code Playgroud)
首先,使用一个字节序将整数打包成二进制格式,然后使用另一个解压缩它(它甚至不管你使用哪种组合,因为你要做的就是交换字节序).
nos*_*nos 25
Big endian意味着32位int的布局首先具有最重要的字节,
例如0x12345678具有内存布局
msb lsb
+------------------+
| 12 | 34 | 56 | 78|
+------------------+
Run Code Online (Sandbox Code Playgroud)
而在小端,内存布局是
lsb msb
+------------------+
| 78 | 56 | 34 | 12|
+------------------+
Run Code Online (Sandbox Code Playgroud)
所以你可以通过一些掩码和移位来转换它们:
def swap32(x):
return (((x << 24) & 0xFF000000) |
((x << 8) & 0x00FF0000) |
((x >> 8) & 0x0000FF00) |
((x >> 24) & 0x000000FF))
Run Code Online (Sandbox Code Playgroud)
Art*_*ich 12
从python 3.2你可以定义函数swap32()如下:
def swap32(x):
return int.from_bytes(x.to_bytes(4, byteorder='little'), byteorder='big', signed=False)
Run Code Online (Sandbox Code Playgroud)
它使用字节数组来表示值,并通过在转换期间将字节顺序更改回整数来反转字节顺序.
| 归档时间: |
|
| 查看次数: |
30655 次 |
| 最近记录: |