|
| 1 | +""" |
| 2 | +Hexadecimal to Decimal |
| 3 | +
|
| 4 | +Author: Ian Doarn |
| 5 | +""" |
| 6 | +from math import pow |
| 7 | + |
| 8 | +hex_letter_values = { |
| 9 | + '0': 0, '1': 1, '2': 2, |
| 10 | + '3': 3, '4': 4, '5': 5, |
| 11 | + '6': 6, '7': 7, '8': 8, |
| 12 | + '9': 9, 'A': 10, 'B': 11, |
| 13 | + 'C': 12, 'D': 13, 'E': 14, |
| 14 | + 'F': 15 |
| 15 | +} |
| 16 | + |
| 17 | + |
| 18 | +def convert_base16_to_base10(h, visualize=False): |
| 19 | + """ |
| 20 | + Convert hexadecimal number to decimal number |
| 21 | + |
| 22 | + Send hex to a list and reverse. Evaluate each hex value |
| 23 | + via hex_letter_values map. Enumerate the list, |
| 24 | + |
| 25 | + using the equation: value * 16 ^ index |
| 26 | + |
| 27 | + value is the hex char value: F -> 15 |
| 28 | + index is its position in the list: ['1', 'A', 'F'] F's index = 2 |
| 29 | + |
| 30 | + Continue this for each hex letter until we reach the end of the list, |
| 31 | + summing all evaluated values. |
| 32 | + |
| 33 | + :param h: hexadecimal number |
| 34 | + :param visualize: Show process |
| 35 | + :return: decimal number |
| 36 | + """ |
| 37 | + |
| 38 | + # Check to see if '0x' is at the beginning and remove it |
| 39 | + if h[0:2] == '0x': |
| 40 | + hex_char_list = list(h[2:])[::-1] |
| 41 | + else: |
| 42 | + hex_char_list = list(h)[::-1] |
| 43 | + |
| 44 | + value = 0 |
| 45 | + |
| 46 | + for i, v in enumerate(hex_char_list): |
| 47 | + if visualize: |
| 48 | + print("{} -> {} || {} * (16 ^ {}) = {}".format( |
| 49 | + v, str(hex_letter_values[v]), |
| 50 | + str(hex_letter_values[v]), |
| 51 | + str(i), |
| 52 | + str(hex_letter_values[v] * (pow(16, i))) |
| 53 | + )) |
| 54 | + |
| 55 | + value += hex_letter_values[v] * (pow(16, i)) |
| 56 | + |
| 57 | + return int(value) |
0 commit comments