Last active
October 24, 2015 19:22
-
-
Save phikal/21c30b75245566989956 to your computer and use it in GitHub Desktop.
Python base n en/de-coder class - Based on http://stackoverflow.com/questions/1119722/base-62-conversion-in-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
BINARY = '01' | |
OCTAL = '01234567' | |
DECIMAL = '0123456789' | |
HEXADEC = '0123456789ABCDEF' | |
BASE_62 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' | |
rev = lambda x: dict((c, i) for i, c in enumerate(x)) | |
used = BASE_62 | |
def encode(NUM, base=used): | |
ret = '' | |
factor = '' | |
blen = len(base) | |
if NUM < 0: | |
NUM *= -1 | |
factor = '-' | |
while NUM != 0: | |
ret += base[NUM % blen] | |
NUM //= blen | |
return factor + ret[::-1] | |
def decode(STR, base=used): | |
ret = 0 | |
factor = 1 | |
rbase = rev(base) | |
blen = len(base) | |
if STR[0] == '-': | |
STR = STR[1:] | |
factor = -1 | |
for i, c in enumerate(reversed(STR)): | |
ret += (blen ** i) * rbase[c] | |
return factor * ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment