Last active
April 28, 2021 08:00
-
-
Save abbasEbadian/a59a0fd6504be087a94ed778af7a66a5 to your computer and use it in GitHub Desktop.
Convert any number from base r1 to base r2 in python where r1, r2 in [2, 36]
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
def change_base(n, r1, r2): | |
if n == 0: | |
return 0 | |
n = to_base10(n, r1) | |
digits = "" | |
while n: | |
digit = int(n % r2) | |
if digit > 9: | |
digit = str(chr(65+digit-10)) | |
digits += str(digit) | |
n //= r2 | |
return digits[::-1] | |
def to_base10(n, b): | |
k = str(n)[::-1] | |
s = 0 | |
for a1, a2 in enumerate(k): | |
if ord(a2) >=65: | |
a2 = 10 + ord(a2)- 65 | |
s += int(a2) * b ** int(a1) | |
return s | |
# input number can be in base 16 e.g 'FF' so it should be in string format. | |
n = input("number : ") | |
r1 = int(input("r1 : ")) | |
r2 = int(input("r2 : ")) | |
print(change_base(n, r1, r2)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment