Search code examples
pythonhexdecimalnumber-systems

python hex to decimal using for loop


import math
def hexToDec(hexi):
    result = 0
    for i in range(len(hexi)-1,-1,-1):
        if hexi[i] == 'A':
            result = result + (10 * math.pow(16,i))
        elif hexi[i] == 'B':
            result = result + (11 * math.pow(16,i))
        elif hexi[i] == 'C':
            result = result + (12 * math.pow(16,i))
        elif hexi[i] == 'D':
            result = result + (13 * math.pow(16,i))
        elif hexi[i] == 'E':
            result = result + (14 * math.pow(16,i))
        elif hexi[i] == 'F':
            result = result + (15 * math.pow(16,i))
        else:
            result = result + (int(hexi[i]) * math.pow(16,i))
    return result

Even after reversing the range order and reimporting I still get the same results.


Solution

  • While there can be beautiful answers like this

    x = int("FF0F", 16)
    

    It's also important to see how the original code went wrong. The corrected version should be:

    import math
    def hexToDec(hexi):
        result = 0
        for i in range(len(hexi)):
            cur_pow = len(hexi) - i  - 1
            if hexi[i] == 'A':
                result = result + (10 * math.pow(16,cur_pow))
            elif hexi[i] == 'B':
                result = result + (11 * math.pow(16,cur_pow))
            elif hexi[i] == 'C':
                result = result + (12 * math.pow(16,cur_pow))
            elif hexi[i] == 'D':
                result = result + (13 * math.pow(16,cur_pow))
            elif hexi[i] == 'E':
                result = result + (14 * math.pow(16,cur_pow))
            elif hexi[i] == 'F':
                result = result + (15 * math.pow(16,cur_pow))
            else:
                result = result + (int(hexi[i]) * math.pow(16,cur_pow))
        return result
    

    Whether you loop in "reverse" or not, the power order and the index to hexi should iterate at the opposite direction, one increasing another decreasing.

    Now you can forget about this and use the answers suggested by others.