Last active
March 1, 2019 00:01
-
-
Save cupof-github/2a7159c701439e03a381e0d3c560de03 to your computer and use it in GitHub Desktop.
base58 encoder and decoder with Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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