July 11th, 2019

IslandT: Convert hexadecimal number to decimal number with Python program

Python, by admin.

Use python program to convert hexadecimal number to the decimal number.

Hello and welcome back, in this article we are going to solve one of the programming problems on Codewars. This problem had been listed under the 8 Kyu category which means if we can solve that problem we will get two points. First I thought this should be an easy and simple question, I always select the 8 or 7 kyu questions not because they are hard but because they are simple. But after I have gone through this question, the only comment from me is “WHAT THE ****!”, man this question should be put under 6 kyu instead of the easiest category! Anyway, let us look at this question.

We will be given a string of hexadecimal number, for example, “C2a3”, we need to convert that hexadecimal number to the decimal number and return the answer to the caller.

If you are having a problem converting hexadecimal number to the decimal number, read this article. I will not go through all the details here because we will just concentrate on the programming part.

Here are the steps we will need to do to solve the above problem.

  1. Convert all the characters in the hexadecimal string to lower case if there is any uppercase character in the string.
  2. Turn the new string into a list.
  3. Create a dictionary object with hexadecimal number as the key and the decimal number as the value.
  4. Reverse the list item (because the first hexadecimal letter starts from the right side of that hexadecimal string) and start to do the conversion within a for loop.
def hex_to_dec(s):
    s = s.lower()
    s_list = list(s)
    hex_dict = {"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}
    count = 0
    sum = 0

    for item in reversed(s_list):
        sum += hex_dict[item] * (16 ** count) # read that hexadecimal post if you are lost
        count+=1
           
    return sum

Leave your own solution in the comment box below this post, as always! But make sure you know what you are talking about, which means please don’t go beyond the subject of this post.

Back Top

Comments are closed.