在将十六进制基数转换为十进制python 3时,如何将字母分配给数字?
我正在编写一段代码,将用户输入的十六进制(以16为基数)数字转换为以10为基数,但我无法使用任何内置python函数,因此看起来如下所示:在将十六进制基数转换为十进制python 3时,如何将字母分配给数字?,python,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
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")
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")
我需要这样做,如果字母A、B、C、D、E或F作为基数16数字的一部分输入,函数将分别识别为10、11、12、13、14和15,并将数字转换为基数10。谢谢 这看起来很像回答家庭作业问题。。。但好了,开始吧。我对这个问题的第一个解决方案是这样的:
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")
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.index
、sum
和枚举
。因此,停止使用这些函数,忽略dictionary下标操作符是对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")
这看起来很像回答家庭作业问题。。。但好了,开始吧。我对这个问题的第一个解决方案是这样的:
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")
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.index
、sum
和枚举
。因此,停止使用这些函数,忽略dictionary下标操作符是对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")
如果您使用的是
int(c)
,那么您是否可以不使用int(base16,16)
?如果您希望这是超级手动的,您可以使用字典将字符转换为int。如果您使用的是int(c)
,您是否可以不使用int(base16,16)
?如果您希望这是超级手动的,您可以使用字典将字符转换为整数。的可能重复项