且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中字节交换32位整数?

更新时间:2023-11-28 15:14:16

一种方法是使用 struct 模块:

One method is to use the struct module:

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).