简体   繁体   English

Python脚本将十六进制转换为十进制

[英]Python script to convert hexadecimal to decimal

I've written the python script below to convert hexadecimal to decimal. 我已经写了下面的Python脚本将十六进制转换为十进制。 It seems to work fine, at least as long as the hexadecimal has less then 8 characters . 至少只要十六进制少于8个字符,它似乎就可以正常工作。

What did I do wrong ? 我做错了什么 ? Tnx ! 天哪!

""" converts hexidecimal to decimal"""
def HextoDec (string):
    ret = 0
    for i in string : 
        hex = "0123456789ABCDEF"
        value= hex.index(i) # 0 to 15  
        index = string.index(i)
        power = (len(string) -(index+1)) #power of 16
        ret += (value*16**power)
    return ret
print(HextoDec("BAABFC7DE"))  

The problem is this line: 问题是这一行:

index = string.index(i)

index() returns the position of the first match. index()返回第一个匹配项的位置。 If the hex number contains any duplicate characters, you'll get the wrong index for all the repeats. 如果十六进制数字包含任何重复的字符,则所有重复的索引都会错误。

Instead of searching for the index, get it directly when you're iterating: 无需搜索索引,而是在迭代时直接获取它:

for index, i in enumerate(string):

There is a much easier way to convert hexadecimal to decimal without the use of a custom function - just use the built-in int() function like so: 有一种不使用自定义函数的将十六进制转换为十进制的简便得多的方法-只需使用内置的int()函数,如下所示:

int("BAABFC7DE", base=16) #replace BAABFC7DE with any hex code you want

But if you do want to use a custom function, then Barmar's answer is the best. 但是,如果您确实想使用自定义函数,那么Barmar的答案是最好的。

As Barmar pointed out. 正如巴尔玛所指出的。 The issued is with the line 发行是随行

index = string.index(i) 索引= string.index(i)

Which returns first match. 返回第一个匹配项。 Try this: 尝试这个:

def HextoDec (string):
    ret = 0
    for i,d in enumerate(string) : 
        hex = "0123456789ABCDEF"
        value= hex.index(d) # 0 to 15
        #index = string.index(i)
        power = (len(string) -(i+1)) #power of 16
        ret += (value*16**power)
    return ret

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

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