Filip
Filip

Reputation: 23

Python script to convert hexadecimal to decimal

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"))  

Upvotes: 2

Views: 6435

Answers (3)

lyxal
lyxal

Reputation: 1118

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.

Upvotes: 2

Haaput
Haaput

Reputation: 55

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

Upvotes: 1

Barmar
Barmar

Reputation: 782499

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):

Upvotes: 4

Related Questions