Skip to content

Instantly share code, notes, and snippets.

@adw0rd
Created April 28, 2020 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adw0rd/8294a5e0eb406f6c40d23e440ae2f501 to your computer and use it in GitHub Desktop.
Save adw0rd/8294a5e0eb406f6c40d23e440ae2f501 to your computer and use it in GitHub Desktop.
class InstagramIdCodec:
ENCODING_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
@staticmethod
def encode(num, alphabet=ENCODING_CHARS):
"""Covert a numeric value to a shortcode."""
num = int(num)
if num == 0:
return alphabet[0]
arr = []
base = len(alphabet)
while num:
rem = num % base
num //= base
arr.append(alphabet[rem])
arr.reverse()
return "".join(arr)
@staticmethod
def decode(shortcode, alphabet=ENCODING_CHARS):
"""Covert a shortcode to a numeric value."""
base = len(alphabet)
strlen = len(shortcode)
num = 0
idx = 0
for char in shortcode:
power = strlen - (idx + 1)
num += alphabet.index(char) * (base ** power)
idx += 1
return num
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment