编写一个函数将十六进制转换为十进制 [英] Writing a function to convert hex to decimal
问题描述
我需要编写一个将十六进制转换为十进制的函数,并且我已经知道如何去做,但我还是停留在第一位.到目前为止,我正在接受用户输入并以十六进制返回它,但这仅在我一次输入 1 件事时才有效.代码是:
def hex(x):如果 x == "0":返回 0elif x == "1":返回 1elif x == "2":返回 2elif x == "3":返回 3elif x == "4":返回 4elif x == "5":返回 5elif x == "6":返回 6elif x == "7":返回 7elif x == "8":返回 8elif x == "9":返回 9elif x == "A":返回 10elif x == "B":返回 11elif x == "C":返回 12elif x == "D":返回 13elif x == "E":返回 14elif x == "F":返回 15打印十六进制(原始输入().上())
例如,如果我输入 C,它会返回 12,但如果我输入 8C,则它不起作用.我不明白这是为什么.
您可以使用 int
使这更容易.功能:
def hex_to_dex(strng_of_hex):返回整数(strng_of_hex,16)
示例:
<预><代码>>>>int("0xff", 16)255int 前面是否有 0x
并不重要,它会忽略字符串中的 0x
.因此,以下内容也将起作用:
对于从头开始的原始十六进制代码,请尝试以下操作:
def 十六进制:_hexer = "0123456789ABCDEF"return sum([_hexer.find(var) * 16 ** i for i, var in enumerate(reversed(s.upper()))])
如果你想放一些守卫:
def 十六进制:_hexer = "0123456789ABCDEF"如果不是全部([s.upper() 中的 var 的 _hexer 中的变量]):打印无效字符串"返回无return sum([_hexer.find(var) * 16 ** i for i, var in enumerate(reversed(s.upper()))])
我在这里使用了很多函数,但为了快速参考,这里有一个附录:
至于 [...]
,它是一个列表推导式,你可以在上面找到大量资源.
I need to write a function that converts hex to decimal and I've got an idea of how to do it but I'm stuck at the first bit. So far I am taking the user input and returning it in hex, but this only works if I enter 1 thing at a time. The code is:
def hex(x):
if x == "0":
return 0
elif x == "1":
return 1
elif x == "2":
return 2
elif x == "3":
return 3
elif x == "4":
return 4
elif x == "5":
return 5
elif x == "6":
return 6
elif x == "7":
return 7
elif x == "8":
return 8
elif x == "9":
return 9
elif x == "A":
return 10
elif x == "B":
return 11
elif x == "C":
return 12
elif x == "D":
return 13
elif x == "E":
return 14
elif x == "F":
return 15
print hex(raw_input().upper())
It works if I enter, for example, C then it returns 12, but if I enter 8C then it doesn't work. I can't figure out why this is.
You can use int
to make this a lot easier. Function:
def hex_to_dex(strng_of_hex):
return int(strng_of_hex, 16)
Example:
>>> int("0xff", 16)
255
It does not matter if you have a 0x
infront for int, it will ignore 0x
in the string. So, the following will also work:
>>> int("a", 16)
10
As for a raw hex code from scratch, try the following:
def hex(s):
_hexer = "0123456789ABCDEF"
return sum([_hexer.find(var) * 16 ** i for i, var in enumerate(reversed(s.upper()))])
If you wanted to put some guards in:
def hex(s):
_hexer = "0123456789ABCDEF"
if not all([var in _hexer for var in s.upper()]):
print "Invalid string"
return None
return sum([_hexer.find(var) * 16 ** i for i, var in enumerate(reversed(s.upper()))])
I've used a lot of functions here, but for quick reference, here's an appendix:
As for the [...]
, its a list comprehension, you can find loads of resources on that.
这篇关于编写一个函数将十六进制转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!