2013-04-02 33 views
3

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

使用结构的非长度特定类型的(虽然我可以做这个错误)似乎不工作:

>> 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' 
+1

你是包装和拆装它作为一个字符串。字符串没有字节顺序。 –

回答

5

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 
+0

谢谢,正是我需要的! – BinaryMage

+0

我还在学习Python,那么有人可以澄清Python 3.3中的等价选项吗?另外,所以我明白,为什么不能用切片来做到这一点?为什么转换为字节? –

1
>>> big = 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000' 
>>> big[::-1] 
'00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff' 
+0

不好,国际海事组织。如果第一个字节是'ef',那么产生的最后一个字节变为'fe',而它应该是'ef'。 – glglgl

+0

@glglgl那么,这取决于它是什么样的大端。假定8位小端字节具有big-endian字节顺序,这可能是一个很好的假设。我只是做了最简单的事情。 :-P –

相关问题