2

I've written the python script below to convert hexadecimal to decimal. It seems to work fine, at least as long as the hexadecimal has less then 8 characters .

What did I do wrong ? Tnx !

""" converts hexidecimal to decimal"""
def HextoDec (string):
    ret = 0
    for i in string : 
        hex = "0123456789ABCDEF"
        value= hex.index(i) # 0 to 15  
        index = string.index(i)
        power = (len(string) -(index+1)) #power of 16
        ret += (value*16**power)
    return ret
print(HextoDec("BAABFC7DE"))  
0

3 Answers 3

4

The problem is this line:

index = string.index(i)

index() returns the position of the first match. If the hex number contains any duplicate characters, you'll get the wrong index for all the repeats.

Instead of searching for the index, get it directly when you're iterating:

for index, i in enumerate(string):
Sign up to request clarification or add additional context in comments.

Comments

2

There is a much easier way to convert hexadecimal to decimal without the use of a custom function - just use the built-in int() function like so:

int("BAABFC7DE", base=16) #replace BAABFC7DE with any hex code you want

But if you do want to use a custom function, then Barmar's answer is the best.

2 Comments

Thanks I know, but since I'm following a course with both an intro to Python and a chapter on hexadecimals, this seemed like a usefull exercise :-)
Of course, I was just suggesting a much friendlier way, hence the reason I referred to @Barmar's answer as being the most helpful.
1

As Barmar pointed out. The issued is with the line

index = string.index(i)

Which returns first match. Try this:

def HextoDec (string):
    ret = 0
    for i,d in enumerate(string) : 
        hex = "0123456789ABCDEF"
        value= hex.index(d) # 0 to 15
        #index = string.index(i)
        power = (len(string) -(i+1)) #power of 16
        ret += (value*16**power)
    return ret

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.