Python 'long' object has no attribute 'to_bytes'?

五迷三道 提交于 2019-12-06 05:38:36

Python 2.7 int and long don't have the .to_bytes method. Python 3.2 int has the .to_bytes method.

A workaround for Python 2.x:

>>> length = 10
>>> n = 123456789
>>> ('%%0%dx' % (length << 1) % n).decode('hex')[-length:]
'\x00\x00\x00\x00\x00\x00\x07[\xcd\x15'

Since Python 3.2 the built-in integer types provide a to_bytes method. https://docs.python.org/3/library/stdtypes.html#int.to_bytes

The code you linked contains :

assert n.to_bytes(length, 'big') == bytes( (n >> i*8) & 0xff for i in reversed(range(length)))

which means that you can define a to_bytes function:

def to_bytes(n, length):
    return bytes( (n >> i*8) & 0xff for i in reversed(range(length)))

And use it as such:

def decode_base58(bc, length):
    n = 0
    for char in bc:
        n = n * 58 + digits58.index(char)
    return to_bytes(n, length)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!