How to convert integer to base58?

2.6k Views Asked by At

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

2

There are 2 best solutions below

0
snakecharmerb On BEST ANSWER

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'
0
Joshua Wolff On

For Python, you can now use b58encode_int

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