Skip to content

Instantly share code, notes, and snippets.

@npanuhin
Last active September 23, 2022 20:37
Show Gist options
  • Save npanuhin/14fcdbe2e39ec0d95fd739cf2f4c1c5b to your computer and use it in GitHub Desktop.
Save npanuhin/14fcdbe2e39ec0d95fd739cf2f4c1c5b to your computer and use it in GitHub Desktop.
Base converter on Python 3
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