0

I'm trying to write a function that converts hexadecimal to decimal. I have two problems. I can't get it to replace all letters with a number. It replaces a letter and then stops. Second, how do I get it so that it consecutively adds each integer?

 def toDecimal(hexidecimal):
    decimal=[hexidecimal[i:i+1] for i in range(0,len(hexidecimal), 1)]
    for i in range(0,len(decimal)):
            if 'a' in decimal:
                decimal[i]='10'
            if 'b' in decimal:
                decimal[i]='11'
            if 'c' in decimal:
                decimal[i]='12'
            if 'd' in decimal:
                decimal[i]='13'
            if 'e' in decimal:
                decimal[i]='14'
            if 'f' in decimal:
                decimal[i]='15'
            return decimal
      #Above I try to convert any letters into a number value 
    for i in range(0,len(decimal)):
        converted_decimal=decimal[i]*(16**i)
        total_decimal=converted_decimal+converted_decimal
    return total_decimal
     #Here I'm trying to add each converted decimal 
3
  • is it an assignement ? otherwise int(hexnumber, 16) does the job Commented Oct 15, 2013 at 8:13
  • Yes, it's an assignment. Commented Oct 15, 2013 at 8:13
  • Try int('0xA', 16) or eval('0xA') Commented Oct 15, 2013 at 8:13

4 Answers 4

2

There are a lot of issues in your code. Let's go through it :

hexidecimal= "7ac8965f" #hexadecimal value

decimal=[hexidecimal[i:i+1] for i in range(0,len(hexidecimal), 1)]
# >> decimal : ["7","a","c","8","9","6","5","f"]

for i in range(0,len(decimal)):
# first path : i = 0

        # First Error : 'in' is a array-wide search.
        # you want to use :'if decimal[i] == 'a' '
        if 'a' in decimal: # a is in decimal (second pos) so decimal[0] is modified !
            decimal[i]='10'
            # >> decimal : ["10","a","c","8","9","6","5","f"]

        if 'b' in decimal:
            decimal[i]='11'
        if 'c' in decimal:
            decimal[i]='12'
        if 'd' in decimal:
            decimal[i]='13'
        if 'e' in decimal:
            decimal[i]='14'
        if 'f' in decimal: # f is in decimal (last pos) so decimal[0] is modified !
            decimal[i]='15'
            # >> decimal : ["15","a","c","8","9","6","5","f"]

        #Second Error : anticipated return
        #Assuming the indentation is correct, the function exit here, on the 
        #first run of the function
        return decimal

Now a solution :

#dict for conversion (there are more elegant ways to do it, 
#                                                        but this is good enough)
conversion_table = { '0' : 0 ,
                     '1' : 1 ,
                     '2' : 2 ,
                     '3' : 3 ,
                      .......
                     'a' : 10 ,
                     'b' : 11 ,
                     ......
                     'f' : 15
                    }

hexidecimal= "7ac8965f" #hexadecimal value

hexa_list=[ digit for digit in hexidecimal]
# same thing as before, just more "elegant"

decimal = [ conversion_table[hex_digit] for hex_digit in hexa_list]
# convert everything in base10

# reduce the list
return reduce( lambda x,y : x*16 + y, decimal )
Sign up to request clarification or add additional context in comments.

Comments

2

I think it would be helpful for you, to read this idiomatic python tutorial: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

def hex2dec(hexadecimal):
    conversion_table = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}

    hex_list = list(hexadecimal)

    for index, number in enumerate(hex_list):
        number = number.upper()   

        if number in conversion_table:
            hex_list[index] = conversion_table[number]

    int_list = [int(number) for number in hex_list]

    return reduce(lambda x, y: x*16+y, int_list)


print hex2dec('7Ac8965f')    # 2059966047

Comments

1

I'm just having a bit of fun here, but to rewrite your function...

def toDecimal(hexadecimal):
    decimal = int(hexadecimal, 16)
    return decimal

toDecimal('0xdeadbeef')

I'm presuming you're re-inventing the wheel just to see how it's done? :)

1 Comment

It's an assignment.Hence I'm not allowed to use int().
0

There is a much simpler way to do this:

Something large:

>>> s = "6f48f8248e828ce82f82"
>>> int(s, 16)
525528725744949635067778L

Something smaller:

>>> int('BF', 16)
191

Adding a 0x in front of the number does not change the end result.

As a function:

def hex2dec(s):
    """return the integer value of a hexadecimal string s"""
    return int(s, 16)

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.