1

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

priestc
  • 33,060
  • 24
  • 83
  • 117
  • What result are you expecting, exactly? – snakecharmerb Dec 09 '18 at 18:15
  • I expect the number 33 to be expressed as a single digit when converted to base58. Is this assumption incorrect? A number less than 58^2 should be expressed as two characters, a number less than 58^6 should be less than 6 chars, etc... In my example, I get a 3 digit result for a number less than 58... – priestc Dec 09 '18 at 18:25
  • And what happens when you do it for an `int` and not a `str`? – Colin Ricardo Dec 09 '18 at 18:26
  • b58encode doesn't take an integer, the error says: a bytes-like object is required (also str), not 'int' – priestc Dec 09 '18 at 18:31

2 Answers2

5

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'
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
3

For Python, you can now use b58encode_int

>>> import base58
>>> base58.b58encode_int(33)
b'a'
Joshua Wolff
  • 2,687
  • 1
  • 25
  • 42