Created
May 7, 2019 09:01
-
-
Save anroopak/3d2f73ced8a8048a9288b4ccbdae1b83 to your computer and use it in GitHub Desktop.
Convert a Decimal to a base and back.
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
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