Last active
September 23, 2022 20:37
-
-
Save npanuhin/14fcdbe2e39ec0d95fd739cf2f4c1c5b to your computer and use it in GitHub Desktop.
Base converter on Python 3
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
from string import ascii_uppercase, digits | |
alphabet = digits + ascii_uppercase | |
def convert_base(n: str, from_base: int = 10, to_base: int = 10) -> str: | |
if isinstance(n, str): | |
n = int(n, from_base) | |
if n < to_base: | |
return alphabet[n] | |
return convert_base(n // to_base, from_base, to_base) + alphabet[n % to_base] | |
# Usage: | |
print(convert_base('FAAC', from_base=16, to_base=2)) # 1111101010101100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment