-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 ?

9
  • Why not just int(c, 16)? Commented Jan 28, 2019 at 16:55
  • 1
    Possible duplicate Convert hex string to int in Python Commented Jan 28, 2019 at 16:58
  • thank you for your awnser but my professor wants that we do it with a function Commented Jan 28, 2019 at 16:58
  • it's not a duplicate Commented Jan 28, 2019 at 17:01
  • If you search on the phrase "Python convert hex to decimal" or "Python convert base", you’ll find resources that can explain it much better than we can in an answer here. Commented Jan 28, 2019 at 17:08

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks you, i'm not asking for people do all the work for me. I asked for clues :)
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.