简体   繁体   中英

How to assign letters to numbers while converting hexadecimal base to decimal python 3?

I am writing a code that converts a user inputted hexadecimal (base 16) number to base 10, but I can't use any built-in python functions, so it looks like this:

def base16TO10(base16):
    value = base16
    hexadecimal = sum(int(c) * (16 ** i) for i, c in    enumerate(value[::-1]))
    print("Base 16 number:" , base16 , "is base 10 number:" , hexadecimal ,"\n") 

I need to make it so that if the letters A, B, C, D, E, or F are inputted as part of a base 16 number, the function will recognize them as 10,11,12,13,14, and 15, respectively, and will convert the number to base 10. Thanks!

This seems a lot like answering a homework problem... but ok, here goes. My first solution to the problem is something like this:

def base16TO10(base16):
    conversion_list = '0123456789ABCDEF'
    hexadecimal = sum(conversion_list.index(c) * (16 ** i) for i, c in enumerate(base16[::-1]))
    print("Base 16 number:" , base16 , "is base 10 number:" , hexadecimal ,"\n")

However, we're still using a bunch of built in Python functions. We use list.index , sum , and enumerate . So, cutting the use of those functions out and ignoring that the dictionary subscript operator is an implicit call to dictionary. __getitem__ dictionary. __getitem__ , I have:

def base16TO10(base16):
    conversion_dict = {'0':0, '1':1, '2':2, '3':3, 
                       '4':4, '5':5, '6':6, '7':7,
                       '8':8, '9':9, 'A':10, 'B':11,
                       'C':12, 'D':13, 'E':14, 'F':15}
    digit=0
    hexadecimal=0
    for c in base16[::-1]:
        hexadecimal += conversion_dict[c] * (16 ** digit)
        digit += 1
    print("Base 16 number:" , base16 , "is base 10 number:" , hexadecimal ,"\n") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM