加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何在Python中将256位大端整数转换为小端?

发布时间:2020-12-20 11:26:19 所属栏目:Python 来源:网络整理
导读:不太复杂,或者我希望如此.我有一个256位十六进制整数编码为大端,我需要转换为小端. Python的struct模块通常就足够了,但 the official documentation没有列出的格式,其大小甚至接近我需要的格式. 使用struct的非长度特定类型(虽然我可能这样做错了)似乎不起作
不太复杂,或者我希望如此.我有一个256位十六进制整数编码为大端,我需要转换为小端. Python的struct模块通常就足够了,但 the official documentation没有列出的格式,其大小甚至接近我需要的格式.

使用struct的非长度特定类型(虽然我可能这样做错了)似乎不起作用:

>> x = 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000'
>> y = struct.unpack('>64s',x)[0] # Unpacking as big-endian
>> z = struct.pack('<64s',y) # Repacking as little-endian
>> print z
'ffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000'

示例代码(应该发生什么):

>> x = 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000'
>> y = endianSwap(x)
>> print y
'00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff'

解决方法

struct模块无法处理256位数.所以你必须手动编码.

首先,您应该将其转换为字节:

x = 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000'
a = x # for having more successive variables
b = a.decode('hex')
print repr(b)
# -> 'xffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffx00x00x00x00'

这样你可以逆转它using @Lennart’s method:

c = b[::-1]
# -> 'x00x00x00x00xffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxff'

d = c.encode('hex')
z = d
print z
# -> 00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读