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] |
为了回答您的原始问题,没有将
要在Python 2.x中打包任意长度的
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' |
以大端顺序输出数字; 对于小端,反转字符串(
您可能可以使用
1 2 3 | >>> import struct >>> struct.pack('>i', 123) '\x00\x00\x00{' |
它不会像