pythonbase58

How to convert integer to base58?


I have a decimal number, and I want to show it on the screen as a base58 string. There is what I have already:

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

This appears to be correct, but since the number is less than 58, shouldn't the resulting base58 string be only one character? I must be missing some step. I think it's because I'm passing in the string '33' not actually the number 33.

When I pass in a straight integer, I get an error:

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

Basically I want to encode a number in base58 so that it uses the least amount of characters as possible...


Solution

  • base58.b58encode expects bytes or a string, so convert 33 to bytes then encode:

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