I want to encode a non-negative integer to ASCII letters and digits. I wrote below code for that, that works, but which I assume too immature to use in production.
#! /usr/bin/env python3
from string import digits, ascii_letters
def encode(number: int, pool: str) -> str:
"""Encode a non-negative integer as string."""
result = ''
pool_size = len(pool)
while number:
number, remainder = divmod(number, pool_size)
result += pool[remainder]
return result
def main():
size = (1 << (8 * 2)) - 1
codes = set()
for i in range(size):
print(i, code := encode(i, digits+ascii_letters))
codes.add(code)
print('Unique:', len(codes) == size)
if __name__ == '__main__':
main()
I also tried the encoding functions in the base64 library to no avail. Most of them will create strings containing other than the desired characters at some point and b16encode() has a too small alphabet, resulting in too long codes (no lower-case).
If you can provide a better solution to convert an arbitrary non-negative integer into a string of characters exclusively from string.ascii_letters + string.digits, that would be great.
Update
Project on GitHub