- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathhexadecimal_to_decimal.py
49 lines (43 loc) · 1.49 KB
/
hexadecimal_to_decimal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
hex_table= {hex(i)[2:]: iforiinrange(16)} # Use [:2] to strip off the leading '0x'
defhex_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")
Traceback (most recent call last):
...
ValueError: Non-hexadecimal value was passed to the function
>>> hex_to_decimal("")
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function
>>> hex_to_decimal("12m")
Traceback (most recent call last):
...
ValueError: Non-hexadecimal value was passed to the function
"""
hex_string=hex_string.strip().lower()
ifnothex_string:
raiseValueError("Empty string was passed to the function")
is_negative=hex_string[0] =="-"
ifis_negative:
hex_string=hex_string[1:]
ifnotall(charinhex_tableforcharinhex_string):
raiseValueError("Non-hexadecimal value was passed to the function")
decimal_number=0
forcharinhex_string:
decimal_number=16*decimal_number+hex_table[char]
return-decimal_numberifis_negativeelsedecimal_number
if__name__=="__main__":
fromdoctestimporttestmod
testmod()