Last active
May 23, 2022 09:22
-
-
Save BibMartin/c4241fcbf2e597f5b1c257b071e1b692 to your computer and use it in GitHub Desktop.
Encode your ints into a short base32 string (case-unsensitive letters and digits)
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
import math | |
import base64 | |
def int_to_b32str(x): | |
base = int(math.log2(1 + x) / 8) + 1 # How many bytes ? | |
bytestring = x.to_bytes(base, 'big') | |
b32str = base64.b32encode(bytestring).decode() | |
return b32str.rstrip('=') # remove trailing "=" | |
def b32str_to_int(b): | |
b32str = b.upper() + "=" * (-len(b) % 8) # Recreate trailing "=" | |
bytestring = base64.b32decode(b32str.encode()) | |
return int.from_bytes(bytestring, 'big') | |
# Test it with : | |
# import random | |
# for i in range(10): | |
# x = random.randint(0, 10**9) | |
# b = int_to_b32str(x) | |
# print(x, '\t', b, '\t', b32str_to_int(b) == x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment