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)


Ned*_*ily 11

为了回答你原来的问题,对象的to_bytes方法int没有从Python 3反向移植到Python 2.7.它被考虑但最终被拒绝.请参阅此处的讨论.


nne*_*neo 7

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]).