Created
March 30, 2016 01:32
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Why not use the standard order and just change the +/ to -_?
I recommend (since b is a parameter) that the ALPHABET and TABLE actually be indexed by
b
like: