[英]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: 我正在编写将用户输入的十六进制(基数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")
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! 我需要这样做,以便如果输入字母A,B,C,D,E或F作为基数16的一部分,则该函数会将其识别为10、11、12、13、14和15 ,并将数字转换为10。谢谢!
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. 但是,我们仍在使用一堆内置的Python函数。 We use list.index
, sum
, and enumerate
. 我们使用list.index
, sum
和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__
的隐式调用dictionary. __getitem__
dictionary. __getitem__
, I have: 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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.