Python 3 to_bytes是否已反向移植到python 2.7?

Has Python 3 to_bytes been back-ported to python 2.7?

这是我需要的功能:-

http://docs.python.org/3/library/stdtypes.html#int.to_bytes

我需要很大的字节序支持。


根据@nneonneo的回答,这是一个模拟to_bytes API的函数:

1
2
3
4
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]


为了回答您的原始问题,没有将int对象的to_bytes方法从Python 3反向移植到Python 2.7。 请参阅此处的讨论。


要在Python 2.x中打包任意长度的long,可以使用以下命令:

1
2
3
4
5
6
>>> n = 123456789012345678901234567890L
>>> h = '%x' % n
>>> s = ('0'*(len(h) % 2) + h).decode('hex')
>>> s
'\x01\x8e\xe9\x0f\xf6\xc3s\xe0\xeeN?
\xd2'

以大端顺序输出数字; 对于小端,反转字符串(s[::-1])。


您可能可以使用struct.pack代替:

1
2
3
>>> import struct
>>> struct.pack('>i', 123)
'\x00\x00\x00{'

它不会像int.to_bytes那样执行任意长度,但是我怀疑您是否需要这样做。