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

前端 未结 3 927
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 17:55

Take this example:

i = 0x12345678
print(\"{:08x}\".format(i))
   # shows 12345678
i = swap32(i)
print(\"{:08x}\".format(i))
   # should print 78563412
         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 18:43

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

提交回复
热议问题