Skip to content

Instantly share code, notes, and snippets.

@HacKanCuBa
Last active January 20, 2022 15:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HacKanCuBa/de5b2e94bb7a59cd753491a439e6c3d5 to your computer and use it in GitHub Desktop.
Save HacKanCuBa/de5b2e94bb7a59cd753491a439e6c3d5 to your computer and use it in GitHub Desktop.
Encode with custom alphabet
def encode_int(number: int, *, alphabet: bytes) -> bytes:
"""Encode given number using the characters from the alphabet."""
if number < 0:
raise ValueError('number must be positive')
if len(alphabet) != len(set(alphabet)):
raise ValueError('characters in the alphabet must be unique')
if number == 0:
return alphabet[0:1]
encoded = []
while number > 0:
number, idx = divmod(number, len(alphabet))
encoded.append(alphabet[idx])
encoded.reverse()
return bytes(encoded)
def encode(value: bytes, *, alphabet: bytes) -> bytes:
"""Encode given value using the characters from the alphabet."""
number = int.from_bytes(value, 'big', signed=False)
return encode_int(number, alphabet=alphabet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment