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

前端 未结 3 925
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  无人及你
    2020-12-15 18:37

    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.

提交回复
热议问题