-1

I have to create a program in Python that will convert a hexadecimal number to a decimal number, for example from FA2 to 4002.

I have to write the function hexa2dec(c) where c is a string input parameter and the returned value is of type int. I've started by creating a dictionary :

dic={"0":0, "1":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "A":10, "B":11, "C":12, "D":13, "E":14, "F":15}

and my code is this:

c = "F"

def hexa2dec(c):

   d = ""   

   if c[0]=="F":

      d = dic["F"]*(16**(len(c)-1))

  return d

But I know that it's very bad, for example I don't know what will the length that a person can enter if this person for example does print(hexa2dec(F4CF)). I know that with len(i) I can know the length but does it help ?

roschach
  • 8,390
  • 14
  • 74
  • 124

2 Answers2

0

Since this is a task set to you by your professor, I'm not going to solve it for you, I'll just give you a few hints:

You can iterate over a string backwards using slice/stride notation: for digit in hex_string[::-1]: will do that.

Now you can use a counter variable, use it to calculate the correct power of 16, and increment it in each loop. If you already know the enumerate() function, that task becomes even easier.

Use a result variable and add the result of each iteration to it.

That should get you started.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

The better way would be to just use one of the preprogrammed functions but since you want to code it yourself, I suggest you try using loops. For example a while loop to perform some math on every digit.