Skip to content

Instantly share code, notes, and snippets.

@rastislavcore
Created October 25, 2016 06:06
Show Gist options
  • Save rastislavcore/f982082f122c610d21450a7e421e999c to your computer and use it in GitHub Desktop.
Save rastislavcore/f982082f122c610d21450a7e421e999c to your computer and use it in GitHub Desktop.
Python
ALPHABET = "bcdfghjklmnpqrstvwxyz0123456789BCDFGHJKLMNPQRSTVWXYZ"
BASE = len(ALPHABET)
MAXLEN = 6
def encode_id(self, n):
pad = self.MAXLEN - 1
n = int(n + pow(self.BASE, pad))
s = []
t = int(math.log(n, self.BASE))
while True:
bcp = int(pow(self.BASE, t))
a = int(n / bcp) % self.BASE
s.append(self.ALPHABET[a:a+1])
n = n - (a * bcp)
t -= 1
if t < 0: break
return "".join(reversed(s))
def decode_id(self, n):
n = "".join(reversed(n))
s = 0
l = len(n) - 1
t = 0
while True:
bcpow = int(pow(self.BASE, l - t))
s = s + self.ALPHABET.index(n[t:t+1]) * bcpow
t += 1
if t > l: break
pad = self.MAXLEN - 1
s = int(s - pow(self.BASE, pad))
return int(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment