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

标签 python struct endianness

不太复杂,我希望如此。我有一个编码为大端的 256 位十六进制整数,我需要将其转换为小端。 Python 的结构模块通常就足够了,但是 the official documentation没有列出大小接近我需要的格式。

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

>> 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)
# -> '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00'

这样就可以反转了using @Lennart's method :

c = b[::-1]
# -> '\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'

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

关于python - 如何在 Python 中将 256 位大端整数转换为小端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15759806/

相关文章:

python - 除以零错误输入到Tkinter消息中供计算器使用

python - 将十六进制字符串转换为长python

c - 将指向结构的指针设置为等于函数返回的另一个指向结构的指针?

Haskell 将套接字绑定(bind)到特定 IP

javascript - JS 中二进制处理的字节顺序

python - 根据数据库查询结果设置类对象的属性值

python - 如何使用 Python 库(例如 Paramiko)与 Telnet 和 SSH 进行链式连接

c - C 中有 'making a struct inaccessible directly' 的术语吗?

c - 十六进制值表示和字节顺序说明

python - 使用另一个列表从数据帧列表添加数据帧