如何在python中字节交换32位整数? [英] How to byte-swap a 32-bit integer in python?

查看:830
本文介绍了如何在python中字节交换32位整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举个例子:

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

什么是 swap32-function()?有没有办法在python中字节交换 int ,理想情况下使用内置工具?

What would be the swap32-function()? Is there a way to byte-swap an int in python, ideally with built-in tools?

推荐答案

一种方法是使用 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).

这篇关于如何在python中字节交换32位整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆