在将十六进制基数转换为十进制python3时,如何将字母分配给数字?

2024-06-10 07:46:24 发布

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

我正在编写一个代码,将用户输入的十六进制(以16为基数)数字转换为以10为基数的数字,但是我不能使用任何内置的python函数,所以看起来是这样的:

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

我需要这样做,如果字母A,B,C,D,E,或F是作为一个基数16数字的一部分输入的,函数将分别识别为10,11,12,13,14,和15,并将数字转换为基数10。谢谢!你知道吗


Tags: 函数代码用户numberforvaluedef数字
1条回答
网友
1楼 · 发布于 2024-06-10 07:46:24

这看起来很像回答家庭作业问题。。。但好吧,开始吧。我对这个问题的第一个解决办法是这样的:

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

但是,我们仍然在使用一些内置的Python函数。我们使用list.indexsumenumerate。因此,去掉这些函数的使用,忽略dictionary subscript操作符是对dictionary. __getitem__的隐式调用,我有:

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

相关问题 更多 >