Python3到_字节是否已向后移植到Python2.7?
这就是我想要的功能:- 我需要big-endianness支持。您可能可以使用:Python3到_字节是否已向后移植到Python2.7?,python,Python,这就是我想要的功能:- 我需要big-endianness支持。您可能可以使用: 它不会像int.to_bytes那样实现任意长度,但我怀疑您是否需要它。要在Python 2.x中打包任意长度longs,可以使用以下方法: >>> n = 123456789012345678901234567890L >>> h = '%x' % n >>> s = ('0'*(len(h) % 2) + h).decode('hex') >>
它不会像
int.to_bytes
那样实现任意长度,但我怀疑您是否需要它。要在Python 2.x中打包任意长度long
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'
这将以大端顺序输出数字;对于little endian,反转字符串(
s[:-1]
)。为了回答您最初的问题,用于int
对象的To_bytes
方法没有从Python3向后移植到Python2.7。它曾被考虑过,但最终被拒绝。请参阅讨论。根据@nneonneo的回答,这里有一个模拟to_字节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]
因此,请使用更广泛的数据类型。如果您需要超过64位,您需要先自己做一些工作。这并不是全部……在Python 3中似乎不起作用:AttributeError:“str”对象没有属性“decode”,因此它不是2/3兼容性的可移植解决方案。对于Python 3.4,您需要“h=hex(n).encode('ascii')[2:]”而不是
len(h)
和zfill
,您可以使用s='{:0{}x}'。格式(n,长度*2)。解码('hex')
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]