Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3到_字节是否已向后移植到Python2.7?_Python - Fatal编程技术网

Python3到_字节是否已向后移植到Python2.7?

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') >>

这就是我想要的功能:-

我需要big-endianness支持。

您可能可以使用:


它不会像
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]