Skip to content

Commit 1385e47

Browse files
mohammadreza490ruppysuppycclauss
authored
Create hexadecimal_to_decimal (TheAlgorithms#2393)
* Create hexadecimal_to_decimal * Update conversions/hexadecimal_to_decimal Co-authored-by: Tapajyoti Bose <44058757+ruppysuppy@users.noreply.github.com> * Update conversions/hexadecimal_to_decimal Co-authored-by: Tapajyoti Bose <44058757+ruppysuppy@users.noreply.github.com> * Update conversions/hexadecimal_to_decimal Co-authored-by: Christian Clauss <cclauss@me.com> * Update hexadecimal_to_decimal * Update hexadecimal_to_decimal * Update hexadecimal_to_decimal * Update hexadecimal_to_decimal * Update hexadecimal_to_decimal * Update conversions/hexadecimal_to_decimal Co-authored-by: Christian Clauss <cclauss@me.com> * Update hexadecimal_to_decimal Added negative hexadecimal conversion to decimal number * Update hexadecimal_to_decimal * Update conversions/hexadecimal_to_decimal Co-authored-by: Christian Clauss <cclauss@me.com> * Update conversions/hexadecimal_to_decimal Co-authored-by: Christian Clauss <cclauss@me.com> * Update hexadecimal_to_decimal * Update hexadecimal_to_decimal Co-authored-by: Tapajyoti Bose <44058757+ruppysuppy@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent c38dec0 commit 1385e47

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

conversions/hexadecimal_to_decimal

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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()

0 commit comments

Comments
 (0)