Project #1
Convert a number to a different base. Positive integers only. No floats.
Do not use existing modules. Do it yourself.
(The exception is converting the base to an integer.)
Create an interactive program to ...
- Ask the user for the input number's base and value
- Ask the user for the output number's base
- Convert the input number (string) to the output number (string)
- Print the original base and number, and the
converted base and number
- loop
Limit the number bases used to 2 to 16.
Note: Number base 0 and 1 do not exist.
Project #2
Convert the program to use a GUI.
Project #3
Add converting to bases 17 to 20.
Project #4
Add converting floats.
Links
Octal
(wikipedia)
Decimal
(Wikipedia)
Hexadecimal
(Wikipedia)
Code Hints
# ----------------------------------------------------------
# convert a string to an integer
# note: 145 base 10 = 221 base 8
# (this code only works with positive integers)
# ----------------------------------------------------------
DIGITS = '0123456789abcdef' # string's digit characters
base = 8 # base to convert from
num = 0 # integer results
string = '221' # string to convert (base 8)
digits = DIGITS[:base] # base digit characters
for char in string.lower():
idx = digits.find(char)
if idx < 0: print('error')
num = num * base + idx
print(f'num = {num} base=10')
How to print base 8 using f strings?
Default f string displays base 10.
# ----------------------------------------------------------
# convert an integer to a string
# note: 145 base 10 = 221 base 8
# (this code only works with positive integers)
# ----------------------------------------------------------
DIGITS = '0123456789abcdef' # string's digit characters
base = 8 # base to convert to
num = 145 # number to convert (base 10)
string = '' # string results
digits = DIGITS[:base] # base digit characters
while num > 0:
char = digits[num % base]
idx = digits.find(char)
if idx < 0: print('error')
string = digits[idx] + string
num = int(num/base)
print(f'string = {string} base={base}')