Skip to content

Instantly share code, notes, and snippets.

@anroopak
Created May 7, 2019 09:01
Show Gist options
  • Save anroopak/3d2f73ced8a8048a9288b4ccbdae1b83 to your computer and use it in GitHub Desktop.
Save anroopak/3d2f73ced8a8048a9288b4ccbdae1b83 to your computer and use it in GitHub Desktop.
Convert a Decimal to a base and back.
import string
def int_to_str_base(decimal: int, base: int) -> str:
other_base = ""
while decimal != 0:
other_base = ALPHANUMERIC_CHARS[decimal % base] + other_base
decimal = int(decimal / base)
if other_base == "":
other_base = "0"
return other_base
def str_to_int_base(alphanumeric: str, base: int) -> int:
other_base = 0
for index, char in enumerate(alphanumeric):
assert isinstance(char, str)
if char.isdecimal():
other_base = other_base * base + int(char)
else:
other_base = other_base * base + (10 + ord(char) - ord('A'))
return other_base
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment