Permalink
Browse files

Added base62 encoding/decoding module

  • Loading branch information...
1 parent 676cc28 commit 76db51964f78f7c0732cc8d2ba012047051cf668 @systemsoverload committed Apr 18, 2012
Showing with 29 additions and 0 deletions.
  1. +29 −0 base62.py
View
@@ -0,0 +1,29 @@
+# Borrowed from the ever helpful SO
+# http://stackoverflow.com/questions/1119722/base-62-conversion-in-python
+#
+ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+
+def encode(num, alphabet=ALPHABET):
+ if (num == 0):
+ return alphabet[0]
+ arr = []
+ base = len(alphabet)
+ while num:
+ rem = num % base
+ num = num // base
+ arr.append(alphabet[rem])
+ arr.reverse()
+ return ''.join(arr)
+
+def decode(string, alphabet=ALPHABET):
+ base = len(alphabet)
+ strlen = len(string)
+ num = 0
+
+ idx = 0
+ for char in string:
+ power = (strlen - (idx + 1))
+ num += alphabet.index(char) * (base ** power)
+ idx += 1
+
+ return num

0 comments on commit 76db519

Please sign in to comment.