Skip to content

Instantly share code, notes, and snippets.

@cupof-github
Last active March 1, 2019 00:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cupof-github/2a7159c701439e03a381e0d3c560de03 to your computer and use it in GitHub Desktop.
Save cupof-github/2a7159c701439e03a381e0d3c560de03 to your computer and use it in GitHub Desktop.
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