简体   繁体   English

Python:十六进制转换代码函数中的语义错误

[英]Python: Semantic error in Hex Conversion Code Function

I have written a function for my 4 hexit hexadecimal to decimal converter, and while it works, there is a semantic error I can't figure out. 我已经为我的4个十六进制十六进制到十进制转换器编写了一个函数,尽管它可以工作,但存在我无法弄清的语义错误。 Could you please tell me what the error is? 您能告诉我错误是什么吗?

def convert16_10(hexa):
    den = 0
    for i in range(4):
        if hexa[i] == "A":
            den += (16 ** 3-i) * 10
        elif hexa[i] == "B":
            den += (16 ** 3-i) *11
        elif hexa[i] == "C":
            den += (16 ** 3-i) * 12
        elif hexa[i] == "D":
            den += (16 ** 3-i) * 13
        elif hexa[i] == "E":
            den += (16 ** 3-i) * 14
        elif hexa[i] == "F":
            den += (16 ** 3-i) * 15
        elif hexa[i] not in "ABCDEF":
            den += (16 ** 3-i) * i
    return den

您可以使用以下代码简单地将其转换:

i = int(hexa, 16)
  • You should use parentheses in the power in (16 ** 3-i) . 您应该在(16 ** 3-i)括号中使用括号。 Should be (16 ** (3-i)) . 应该是(16 ** (3-i))
  • You should multiply the digit after converting it to an integer instead of the index in * i . 将数字转换为整数而不是* i中的索引后,应乘以该数字。 Should be * int(hexa[i]) . 应该是* int(hexa[i])

Solution: 解:

def convert16_10(hexa):
    den = 0
    for i in range(4):
        if hexa[i] == "A":
            den += (16 ** (3-i)) * 10
        elif hexa[i] == "B":
            den += (16 ** (3-i)) *11
        elif hexa[i] == "C":
            den += (16 ** (3-i)) * 12
        elif hexa[i] == "D":
            den += (16 ** (3-i)) * 13
        elif hexa[i] == "E":
            den += (16 ** (3-i)) * 14
        elif hexa[i] == "F":
            den += (16 ** (3-i)) * 15
        elif hexa[i] not in "ABCDEF":
            den += (16 ** (3-i)) * int(hexa[i])
    return den

print(convert16_10("007F")) # => 127

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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