-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_converter.py
63 lines (48 loc) · 1.72 KB
/
base_converter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'''
This project allows the user to convert from one base to another.
It supports bases 2 through 16.
'''
def decimal_to_others(num, new_base):
"""
This function converts numbers from decimal to bases 2 through 16.
"""
# Request for user input and initialize state variable.
result = ''
num = int(num)
new_base = int(new_base)
# Do long division and accumulate the remainders.
while num > 0:
rem = num % new_base
if rem >= 10:
rem = chr(55 + rem) # Map to appropriate letter if remainder is less greater than 9.
num = num // new_base
result = str(rem) + result
return result
def others_to_decimal(num, num_base):
"""
This function converts numbers from base 2 through 16 to base 10.
"""
result = 0
power = len(num) - 1
for i in num:
if ord('A') <= ord(i) <= ord('Z'): # Check for remainders greater than 9
result += (ord(i) - 55) * int(num_base)**(power)
else:
result += int(i) * int(num_base)**(power)
power -= 1
return result
def main():
print('Please enter the type of conversion to perform: ')
print('- Enter 1 for "Decimal to other bases conversion"\n- Enter 2 for "Other bases to Decimal conversion"')
conv_type = int(input('--> '))
num = input("Enter number: ")
base = input("Enter base: ")
if 2 <= int(base) <= 16:
if conv_type == 1:
print(f'{num} to base 10 = {decimal_to_others(num, base)} to base {base}.')
if conv_type == 2:
print(f'{num} to base {base} = {others_to_decimal(num, base)} to base 10')
else:
print('Invalid input!\nBase must be between 2 and 16!')
if __name__ == '__main__':
main()