简体   繁体   中英

convert hex to decimal value using python?

I want to convert hex to decimal value for the bellow given .txt file . specifically in line number 1, only for 73cb for that purposes I have developed python program . BUT it does not work and my output should be: 29643

(10 (0 1 73cb 0))
(13 (0 1 e7ba 0))
(12 (0 1 0 0))
(10 (2 1 73cb 1 3)(
-0.05492209987825172 0.2133354572857093 0.2934898883481872
-0.05491927490082463 0.211290383138306 0.2817208459424883
-0.04367581308239386 0.212758053576771 0.287530716703097
))

with open("test.txt","r") as fi:
    id = []
    for ln in fi:
        if ln.startswith("(10"):
            id.append(ln[9:13])
            sd=print(id)
            dec=int(sd,16)
            print(dec)

You have assigned the value of variable sd to print() which will return None .

What you need to do is to convert the ln[9:13] to int and then convert it from hexadecimal to decimal.

A code modified from yours is

with open("test.txt","r") as fi:
    id = []
    for ln in fi:
        if ln.startswith("(10"):
            sd=ln[9:13]
            id.append(sd)
            dec=int(sd,16)
            print(dec)

Additionally, I would recommend changing the variable name id to something else since id is the name of an inbuilt function in python. Using id as a variable name will cause function overriding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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