python中十六进制到十进制的转换

2024-06-26 15:04:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个函数,把十六进制转换成十进制。 我有两个问题。我无法用数字代替所有的字母。它替换一个字母,然后停止。第二,我如何得到它,使它连续地加上每个整数?在

 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 

Tags: to函数inforlenreturnif字母
3条回答

我认为阅读这个习惯用法的python教程会对您有所帮助: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

你的代码中有很多问题。让我们来看看:

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

现在有一个解决方案:

^{pr2}$

我只是有点好玩,但是要重写你的函数。。。在

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

toDecimal('0xdeadbeef')

我想你发明轮子只是为了看看它是怎么做的?:)

相关问题 更多 >