File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x'
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
+ ValueError: Non-hexadecimal value was passed to the function
21
+ >>> hex_to_decimal("")
22
+ ValueError: Empty string value was passed to the function
23
+ >>> hex_to_decimal("12m")
24
+ ValueError: Non-hexadecimal value was passed to the function
25
+ """
26
+ hex_string = hex_string.strip().lower()
27
+ if not hex_string:
28
+ raise ValueError("Empty string was passed to the function")
29
+ is_negative = hex_string[0] == "-"
30
+ if is_negative:
31
+ hex_string = hex_string[1:]
32
+ if not all(char in hex_table for char in hex_string):
33
+ raise ValueError("Non-hexadecimal value was passed to the function")
34
+ decimal_number = 0
35
+ for char in hex_string:
36
+ decimal_number = 16 * decimal_number + hex_table[char]
37
+ if is_negative:
38
+ decimal_number = -decimal_number
39
+ return decimal_number
40
+
41
+
42
+ if __name__ == "__main__":
43
+ from doctest import testmod
44
+
45
+ testmod()
You can’t perform that action at this time.
0 commit comments