首页 > 解决方案 > 如何将整数转换为base58?

问题描述

我有一个十进制数,我想在屏幕上将其显示为 base58 字符串。我已经有了:

>>> from base58 import b58encode
>>> b58encode('33')
'4tz'

这似乎是正确的,但是由于数字小于 58,因此生成的 base58 字符串不应该只有一个字符吗?我一定错过了一些步骤。我认为这是因为我传入的字符串 '33' 实际上不是数字 33。

当我传入一个直整数时,我收到一个错误:

>>> b58encode(33)
TypeError: a bytes-like object is required (also str), not 'int'

基本上我想在base58中编码一个数字,以便它使用尽可能少的字符......

标签: pythonbase58

解决方案


base58.b58encode需要字节或字符串,因此将 33 转换为字节然后编码:

>>> base58.b58encode(33)
Traceback (most recent call last):
...
TypeError: a bytes-like object is required (also str), not 'int'
>>> i = 33
>>> bs = i.to_bytes(1, sys.byteorder)
>>> bs
b'!'
>>> base58.b58encode(bs)
b'a'

推荐阅读