Skip to content

Instantly share code, notes, and snippets.

@jsundram
Created March 30, 2016 01:32
Show Gist options
  • Select an option

  • Save jsundram/68d46de72d1f52dc362631c3588e5cf3 to your computer and use it in GitHub Desktop.

Select an option

Save jsundram/68d46de72d1f52dc362631c3588e5cf3 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]
@dlamblin
Copy link
Copy Markdown

dlamblin commented Dec 13, 2018

Why not use the standard order and just change the +/ to -_?

ALPHABET='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'  #or
ALPHABET='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'

I recommend (since b is a parameter) that the ALPHABET and TABLE actually be indexed by b like:

ALPHABET={
    56: '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz',
    58: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz',
    64: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
    '64u': 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
}
TABLE={b:{c: i for (i,c) in enumerate(ALPHABET[b])} for b in ALPHABET}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment