【问题标题】:How to convert integer to base58?如何将整数转换为base58?
【发布时间】:2019-05-10 17:38:07
【问题描述】:

我有一个十进制数,我想在屏幕上将其显示为 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 中编码一个数字,以便它使用尽可能少的字符...

【问题讨论】:

  • 您到底期待什么结果?
  • 我希望数字 33 在转换为 base58 时以单个数字表示。这个假设不正确吗?小于 58^2 的数字应表示为两个字符,小于 58^6 的数字应小于 6 个字符,等等...在我的示例中,对于小于 58 的数字,我得到 3 位结果。 .
  • 当您为int 而不是str 这样做时会发生什么?
  • b58encode 不接受整数,错误提示:需要一个类似字节的对象(也是 str),而不是 'int'

标签: python base58


【解决方案1】:

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'

【讨论】:

    【解决方案2】:

    对于 Python,您现在可以使用 b58encode_int

    >>> import base58
    >>> base58.b58encode_int(33)
    b'a'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-06
      • 2011-04-04
      • 2021-01-04
      • 2014-11-13
      • 1970-01-01
      • 2017-06-27
      • 2019-10-05
      • 2017-01-26
      相关资源
      最近更新 更多