Reputation: 27
I try to convert decimal to binary, octa and hexadecimal, i need the output to be like this using recursion and without built-in
Decimal: 10
Decimal to Binary: 01010
Decimal to Octa: 12
Decimal to Hexa: A
So far i just got this solving way without recursion
decimal = int(input("Input decimal:"))
#convert binary
def bin(decimal):
if decimal >= 1:
bi(decimal // 2)
return decimal % 2
#convert octa
def octa(decimal):
if decimal >= 1:
octa(decimal // 8)
return decimal % 8
def hex(decimal):
if decimal >= 1:
hex(decimal // 16)
return decimal % 16
Is there a way to make it more simple just using one def
with recursion?
Upvotes: 0
Views: 1015
Reputation: 17166
Can be done with a single recursive function as follows:
Code
def convert(n, base, digits = "0123456789ABCDEF"):
' Function to convert decimal number binary another base '
if n >= base:
return convert(n//base, base) + digits[n%base]
else:
return digits[n]
Test
n = 10 # Decimal number
for base in [2, 8, 16]: # Bases
print(f'Decimal {n} to base {base} = {convert(n, base)}')
Output
Decimal 10 to base 2 = 1010
Decimal 10 to base 8 = 12
Decimal 10 to base 16 = A
Upvotes: 1
Reputation: 192
Yes you can do it by taking the number and the base as the input As we know that the base value is 2 for binary, 8 for octal, 16 for hexadecimal Try the following code
import math
def func(num, base):
count=0
while int(num/math.pow(base,(count+1))) > 0:
count=count+1
new = []
while num >= 0:
p = math.pow(base,count)
if p == 1:
new.append(num)
break
new.append(int(num / p))
num = num- new[-1]*p
count=count-1
s=""
for i in new:
s=s+str(int(i))
return s
num=int(input())
base=int(input())
print(func(num,base))
Upvotes: 0