Reputation: 23
x=""
def main():
Decimal=int(input("Enter a decimal value"))
print (DecimaltoHexa(Decimal))
def HexaLetters(Hexa):
this is where the hexa gets imported here for numbers greater than 9
if Hexa==10:
return "A"
elif Hexa==11:
return "B"
elif Hexa==12:
return "C"
elif Hexa==13:
return "D"
elif Hexa==14:
return "E"
elif Hexa==15:
return "F"
def DecimaltoHexa(Decimal):
need help here as this is the body of the program, i cant use loops because i have to add a recursive function but i need help in doing that.
global x
y=0
LastDigit=0
Hexa=Decimal%16
if Hexa>9:
Hexa=HexaLetters(Hexa)
Decimal=int(Decimal/16)
if Decimal<16:
y=-1
LastDigit=Decimal
x=str(Hexa)+x
final=str(LastDigit)+x
return (final)
DecimaltoHexa(Decimal)
main()
Upvotes: 0
Views: 130
Reputation: 419
Modify your recursive method in the following way to convert a decimal to hexa-
def main():
Decimal=int(input("Enter a decimal value"))
print (DecimaltoHexa(Decimal, ""))
def HexaLetters(Hexa):
if Hexa == 10:
return "A"
elif Hexa == 11:
return "B"
elif Hexa == 12:
return "C"
elif Hexa == 13:
return "D"
elif Hexa == 14:
return "E"
elif Hexa == 15:
return "F"
def DecimaltoHexa(Decimal, prev_hexa):
remainder = Decimal % 16
remaining_Decimal = Decimal // 16
hexa_char = str(remainder)
if remainder > 9:
hexa_char = HexaLetters(remainder)
current_hexa = hexa_char + prev_hexa
if remaining_Decimal != 0:
current_hexa = DecimaltoHexa(remaining_Decimal, current_hexa)
return current_hexa
main()
But if you want a more concise solution, you can use the following implementation -
hexa_chars = map(str, range(10)) + ["A", "B", "C", "D", "E", "F"]
def int_to_hexa(decimal, curr_hexa):
rem = decimal % 16
rem_decimal = decimal // 16
curr_hexa = hexa_chars[rem] + curr_hexa
if rem_decimal:
curr_hexa = int_to_hexa(rem_decimal, curr_hexa)
return curr_hexa
if __name__ == '__main__':
dec = input()
hexa_num = ""
hexa_num = int_to_hexa(dec, hexa_num)
print(hexa_num)
Upvotes: 1