2020-09-04 13:48:44 +00:00
|
|
|
hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x'
|
|
|
|
|
|
|
|
|
|
|
|
def hex_to_decimal(hex_string: str) -> int:
|
|
|
|
"""
|
|
|
|
Convert a hexadecimal value to its decimal equivalent
|
|
|
|
#https://www.programiz.com/python-programming/methods/built-in/hex
|
|
|
|
|
|
|
|
>>> hex_to_decimal("a")
|
|
|
|
10
|
|
|
|
>>> hex_to_decimal("12f")
|
|
|
|
303
|
|
|
|
>>> hex_to_decimal(" 12f ")
|
|
|
|
303
|
|
|
|
>>> hex_to_decimal("FfFf")
|
|
|
|
65535
|
|
|
|
>>> hex_to_decimal("-Ff")
|
|
|
|
-255
|
|
|
|
>>> hex_to_decimal("F-f")
|
2020-09-13 11:27:20 +00:00
|
|
|
Traceback (most recent call last):
|
2022-10-27 17:42:30 +00:00
|
|
|
...
|
2020-09-04 13:48:44 +00:00
|
|
|
ValueError: Non-hexadecimal value was passed to the function
|
|
|
|
>>> hex_to_decimal("")
|
2020-09-13 11:27:20 +00:00
|
|
|
Traceback (most recent call last):
|
2022-10-27 17:42:30 +00:00
|
|
|
...
|
2020-09-13 11:27:20 +00:00
|
|
|
ValueError: Empty string was passed to the function
|
2020-09-04 13:48:44 +00:00
|
|
|
>>> hex_to_decimal("12m")
|
2020-09-13 11:27:20 +00:00
|
|
|
Traceback (most recent call last):
|
2022-10-27 17:42:30 +00:00
|
|
|
...
|
2020-09-04 13:48:44 +00:00
|
|
|
ValueError: Non-hexadecimal value was passed to the function
|
|
|
|
"""
|
|
|
|
hex_string = hex_string.strip().lower()
|
2020-09-13 11:27:20 +00:00
|
|
|
if not hex_string:
|
2020-09-04 13:48:44 +00:00
|
|
|
raise ValueError("Empty string was passed to the function")
|
|
|
|
is_negative = hex_string[0] == "-"
|
|
|
|
if is_negative:
|
|
|
|
hex_string = hex_string[1:]
|
|
|
|
if not all(char in hex_table for char in hex_string):
|
|
|
|
raise ValueError("Non-hexadecimal value was passed to the function")
|
|
|
|
decimal_number = 0
|
|
|
|
for char in hex_string:
|
|
|
|
decimal_number = 16 * decimal_number + hex_table[char]
|
2020-09-13 11:27:20 +00:00
|
|
|
return -decimal_number if is_negative else decimal_number
|
2020-09-04 13:48:44 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
from doctest import testmod
|
|
|
|
|
|
|
|
testmod()
|