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
(hex_string: str)
| 2 | |
| 3 | |
| 4 | def hex_to_decimal(hex_string: str) -> int: |
| 5 | """ |
| 6 | Convert a hexadecimal value to its decimal equivalent |
| 7 | #https://www.programiz.com/python-programming/methods/built-in/hex |
| 8 | |
| 9 | >>> hex_to_decimal("a") |
| 10 | 10 |
| 11 | >>> hex_to_decimal("12f") |
| 12 | 303 |
| 13 | >>> hex_to_decimal(" 12f ") |
| 14 | 303 |
| 15 | >>> hex_to_decimal("FfFf") |
| 16 | 65535 |
| 17 | >>> hex_to_decimal("-Ff") |
| 18 | -255 |
| 19 | >>> hex_to_decimal("F-f") |
| 20 | Traceback (most recent call last): |
| 21 | ... |
| 22 | ValueError: Non-hexadecimal value was passed to the function |
| 23 | >>> hex_to_decimal("") |
| 24 | Traceback (most recent call last): |
| 25 | ... |
| 26 | ValueError: Empty string was passed to the function |
| 27 | >>> hex_to_decimal("12m") |
| 28 | Traceback (most recent call last): |
| 29 | ... |
| 30 | ValueError: Non-hexadecimal value was passed to the function |
| 31 | """ |
| 32 | hex_string = hex_string.strip().lower() |
| 33 | if not hex_string: |
| 34 | raise ValueError("Empty string was passed to the function") |
| 35 | is_negative = hex_string[0] == "-" |
| 36 | if is_negative: |
| 37 | hex_string = hex_string[1:] |
| 38 | if not all(char in hex_table for char in hex_string): |
| 39 | raise ValueError("Non-hexadecimal value was passed to the function") |
| 40 | decimal_number = 0 |
| 41 | for char in hex_string: |
| 42 | decimal_number = 16 * decimal_number + hex_table[char] |
| 43 | return -decimal_number if is_negative else decimal_number |
| 44 | |
| 45 | |
| 46 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected