Skip to content

Instantly share code, notes, and snippets.

@uvicorn
Created September 25, 2020 17:09
Show Gist options
  • Save uvicorn/b5a150b0ce21271d53bb3185aafab63b to your computer and use it in GitHub Desktop.
Save uvicorn/b5a150b0ce21271d53bb3185aafab63b to your computer and use it in GitHub Desktop.
def convert_base(num, to_base=10, from_base=10):
# first convert to decimal number
if isinstance(num, str):
n = int(num, from_base)
else:
n = int(num)
# now convert decimal to 'to_base' base
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n < to_base:
return alphabet[n]
else:
return convert_base(n // to_base, to_base) + alphabet[n % to_base]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment