struct.pack()函数允许将最多64位的整数转换为字节串.打包更大整数的最有效方法是什么?我宁愿不添加像PyCrypto这样的非标准模块的依赖(它提供了num_to_bytes()).
遇到了同样的问题。从python 3.2开始,您可以使用int.to_bytes:
>>> (2**100).to_bytes(16, byteorder='big')
b'\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
Run Code Online (Sandbox Code Playgroud)
你的意思是这样的:
def num_to_bytes(num):
bytes = []
num = abs(num) # Because I am unsure about negatives...
while num > 0:
bytes.append(chr(num % 256))
num >>= 8
return ''.join(reversed(bytes))
def bytes_to_num(bytes):
num = 0
for byte in bytes:
num <<= 8
num += ord(byte)
return num
for n in (1, 16, 256, 257, 1234567890987654321):
print n,
print num_to_bytes(n).encode('hex'),
print bytes_to_num(num_to_bytes(n))
Run Code Online (Sandbox Code Playgroud)
哪个回报:
1 01 1
16 10 16
256 0100 256
257 0101 257
1234567890987654321 112210f4b16c1cb1 1234567890987654321
Run Code Online (Sandbox Code Playgroud)
我只是不确定如何处理否定因素...我不熟悉那些喋喋不休.
编辑:另一种解决方案(我的测试运行速度提高了约30%):
def num_to_bytes(num):
num = hex(num)[2:].rstrip('L')
if len(num) % 2:
return ('0%s' % num).decode('hex')
return num.decode('hex')
def bytes_to_num(bytes):
return int(bytes.encode('hex'), 16)
Run Code Online (Sandbox Code Playgroud)