Skip to content

Instantly share code, notes, and snippets.

@BibMartin
Last active May 23, 2022 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BibMartin/c4241fcbf2e597f5b1c257b071e1b692 to your computer and use it in GitHub Desktop.
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)
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