-
-
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.
This file contains hidden or 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