Skip to content

Instantly share code, notes, and snippets.

@nazmulmithu006
Forked from jsundram/base64.py
Created October 15, 2018 04:56
Show Gist options
  • Select an option

  • Save nazmulmithu006/018313f759231ed0849633154578e102 to your computer and use it in GitHub Desktop.

Select an option

Save nazmulmithu006/018313f759231ed0849633154578e102 to your computer and use it in GitHub Desktop.
base64 encoding for integers. To make long numbers (i.e. hashes) more readable. Not as cool as RFC 1751, but less code.
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_'
TABLE = {c: i for (i, c) in enumerate(ALPHABET)}
def decode(s, b=64):
"""Interpret the input string as a base b number"""
i, multiplier = 0, 1
for c in reversed(s):
i += multiplier * TABLE[c]
multiplier *= b
return i
def encode(h, b=64):
"""Given an hex string, convert to a base b number."""
assert b <= len(ALPHABET)
i = int(h, 16) # hex -> decimal
s = ''
while 0 < i:
i, d = divmod(i, b)
s += ALPHABET[d]
return s[::-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment