Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
base58 encoder and decoder with Python.
"""
Foked from ( * Javascript ) :
inflammable/base58.js : ( https://gist.github.com/inflammable/2929362 )
Description:
- Base58 encoder and decoder, but re-written with Python. This is very covenient to generating 'shorting URL' from integer value ( like, article or post ID based database).
- you can encode to base58 string from Integer value.
- you can decode to Integer from base 58 String value.
Usage:
encode(integer) :
```
shortURL = ShortURL()
num = 335555555
# vDNYB
shortURL.encode(num)
```
decode(string) :
```
shortURL = ShortURL()
# 335555555
shortURL.encode('vDNYB')
```
Tested:
- python 3.6.3
"""
import math
class ShortURL(object):
def __init__(self):
self.baseString = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPRSTUVWXYZ"
self.baseLength = len(self.baseString)
def encode(self, num):
if not int(num):
raise ValueError('must be integer')
pass
encode = ''
while num:
remainder = (num % self.baseLength)
num = math.floor(num / self.baseLength)
encode += self.baseString[remainder]
pass
return encode[::-1]
pass
def decode(self, key):
if not str(key):
raise ValueError('must be String')
pass
decode = 0
while key:
position = self.baseString.index(key[0])
if position < 0:
raise ValueError("'decode' can not find in the baseString")
pass
powerOf = len(key) - 1
decode += position * math.pow(self.baseLength, powerOf)
key = key[1::1]
pass
return int(decode)
pass
# call ShortURL class
shortURL = ShortURL()
num = 335555555
# vDNYB
print(shortURL.encode(num))
# 335555555
print(num)
# 335555555
print(shortURL.decode("vDNYB"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment