这是我追求的功能: -
http://docs.python.org/3/library/stdtypes.html#int.to_bytes
我需要大的字节顺序支持.
mir*_*e2k 15
根据@nneonneo的答案,这是一个模拟to_bytes API的函数:
def to_bytes(n, length, endianess='big'):
h = '%x' % n
s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')
return s if endianess == 'big' else s[::-1]
Run Code Online (Sandbox Code Playgroud)
要long在Python 2.x中打包任意长度的s,您可以使用以下命令:
>>> n = 123456789012345678901234567890L
>>> h = '%x' % n
>>> s = ('0'*(len(h) % 2) + h).decode('hex')
>>> s
'\x01\x8e\xe9\x0f\xf6\xc3s\xe0\xeeN?\n\xd2'
Run Code Online (Sandbox Code Playgroud)
这以big-endian顺序输出数字; 对于小端,反转字符串(s[::-1]).