How to byte-swap a 32-bit integer in python?

会有一股神秘感。 提交于 2019-11-30 08:17:31

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

Big endian means the layout of a 32 bit int has the most significant byte first,

e.g. 0x12345678 has the memory layout

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

From python 3.2 you can define function swap32() as the following:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!