Last active
January 20, 2022 15:01
-
-
Save HacKanCuBa/de5b2e94bb7a59cd753491a439e6c3d5 to your computer and use it in GitHub Desktop.
Encode with custom alphabet
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
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