我有这段Python代码来完成这个任务:
from struct import pack as _pack
def packl(lnum, pad = 1):
if lnum < 0:
raise RangeError("Cannot use packl to convert a negative integer "
"to a string.")
count = 0
l = []
while lnum > 0:
l.append(lnum & 0xffffffffffffffffL)
count += 1
lnum >>= 64
if count <= 0:
return '\0' * pad
elif pad >= 8:
lens = 8 * count % pad
pad = ((lens != 0) and (pad - lens)) or 0
l.append('>' + 'x' * pad + 'Q' * count)
l.reverse()
return _pack(*l)
else:
l.append('>' + 'Q' * count)
l.reverse()
s = _pack(*l).lstrip('\0')
lens = len(s)
if (lens % pad) != 0:
return '\0' * (pad - lens % pad) + s
else:
return s
在我的计算机上,将
2 ** 9700 - 1
转换为字节字符串大约需要174微秒。如果我愿意使用Python 2.7和Python 3.x特定的bit_length
方法,在最开始就预分配l
数组的确切大小,并使用l[something] =
语法而不是l.append
,则可以将时间缩短至159微秒。有什么办法可以使这个过程更快吗?这将用于转换用于加密的大型质数以及一些(但不多)较小的数字。 编辑 在Python < 3.2中,这是当前最快的选项,无论是向前还是向后,所需时间约为接受的答案的一半。
def packl(lnum, padmultiple=1):
"""Packs the lnum (which must be convertable to a long) into a
byte string 0 padded to a multiple of padmultiple bytes in size. 0
means no padding whatsoever, so that packing 0 result in an empty
string. The resulting byte string is the big-endian two's
complement representation of the passed in long."""
if lnum == 0:
return b'\0' * padmultiple
elif lnum < 0:
raise ValueError("Can only convert non-negative numbers.")
s = hex(lnum)[2:]
s = s.rstrip('L')
if len(s) & 1:
s = '0' + s
s = binascii.unhexlify(s)
if (padmultiple != 1) and (padmultiple != 0):
filled_so_far = len(s) % padmultiple
if filled_so_far != 0:
s = b'\0' * (padmultiple - filled_so_far) + s
return s
def unpackl(bytestr):
"""Treats a byte string as a sequence of base 256 digits
representing an unsigned integer in big-endian format and converts
that representation into a Python integer."""
return int(binascii.hexlify(bytestr), 16) if len(bytestr) > 0 else 0
在Python 3.2中,
int
类具有to_bytes
和from_bytes
函数,可以比上述方法更快地完成此操作。
pad
是什么作用?一个文档字符串会很方便地理解它的用法。 - Scott Griffiths