-
-
Save agharbeia/5d3dc0e6998c0f1458dd9b35e57118db to your computer and use it in GitHub Desktop.
Base62 encode/decode tools (convert number to string)
This file contains hidden or 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
#!/usr/bin/env python | |
#-*- coding:utf-8 -*- | |
# Base62 tools (convert number <=> string) | |
# v1.0/20161228 | |
# python 2.x/3.x supported | |
# | |
# based on work by Ady Liu <imxylz@gmail.com> | |
#author: Ahmad gharbeia <ahmad@arabdigitalexpression.org> | |
#github: github.com/agharbeia | |
import sys | |
digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' | |
radix = len(digits) | |
def decode(s): | |
n, exp = 0, 1 | |
for d in reversed(s): | |
n += exp*digits.index(d) | |
exp *= radix | |
return n | |
def encode(n): | |
if n < 0 : raise Exception("negatice number " + n + " entered") | |
if n == 0 : return '0' | |
s = '' | |
while n != 0: | |
s = (digits[n % radix]) + s | |
n = int(n / radix) | |
return s | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
print("Usage: base62.py <num>...") | |
sys.exit(1) | |
width = max(len(x) for x in sys.argv[1:]) | |
for argv in sys.argv[1:]: | |
try: | |
num = int(argv) | |
print('%*s %s %s' % (width,argv,'ENCODE',encode(num))) | |
except ValueError: | |
print('%*s %s %s' % (width,argv,'DECODE',decode(argv))) |
This file contains hidden or 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
$ python base62.py 16075652386131968 1bCQSgeUyk | |
16075652386131968 ENCODE 1bCQSgeUyk | |
1bCQSgeUyk DECODE 16075652386131968 | |
$ python3 base62.py 16075652386131968 1bCQSgeUyk | |
16075652386131968 ENCODE 1bCQSgeUyk | |
1bCQSgeUyk DECODE 16075652386131968 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment