priestc
priestc

Reputation: 35150

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

Upvotes: 1

Views: 2983

Answers (2)

Joshua Wolff
Joshua Wolff

Reputation: 3342

For Python, you can now use b58encode_int

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

Upvotes: 3

snakecharmerb
snakecharmerb

Reputation: 55599

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'

Upvotes: 5

Related Questions