简体   繁体   中英

Converting hexadecimal to decimal using dictionaries

Basically:

I am trying to convert hex to decimal using dictionaries but I can't figure out how I would convert it. I have tried using a for loop to iterate over the hexadecimal value that the user enters, and to convert each one by multiplying it to a power of 16 depending on the length of hex. For example, if the user enters F21, the program should recognise that the length is 3 so should start by multiplying 15(F) by 16^2 and add this to 2*16^1 and add this to 1*16^0. But I come across so many errors

Hexadecimal to Decimal Dictionary:

hex_to_decimal = {
    "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"
}

Note:

I am not trying to use this solution as I am trying to practice dictionaries

s = "F21"
i = int(s, 16)

Since you are converting to decimals, the default base for integers, you should make the values of hex_to_demical integers rather than strings, so that you can perform numeric operations on each translated hex number:

hex_to_decimal = {
    "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
}
def convert(s):
    i = 0
    for h in s:
        i = i *16 + hex_to_decimal[h]
    return i

with the above code,

convert('F21')

would return:

3873

A one-liner, using enumerate and sum :

def conv(s):
    return sum(16**i*int(hex_to_decimal[x]) for i, x in enumerate(s[::-1]))

conv('FF')
# 255
conv('A1')
# 161
conv('F21')
# 3873

Simply look over both the index i and the digit n of the hex string using enumerate() , and do the computation n_dec*16**i (eg with n_dec = 15 when n = F ). Specifically, we have n_dec = int(hex_to_decimal[n]) , with the int() needed because you store the values of your dict as str s. Finally, sum everything up:

s_hex = "F21"
s_dec = str(sum(
    int(hex_to_decimal[n])*16**i for i, n in enumerate(reversed(s_hex))
))

The reversed() is needed because the first (hexadecimal) digits refer to the larger values. The str() is used just to keep the final decimal result as a str , just as the values in your dict .

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