Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create hexadecimal_to_decimal #2393

Merged
merged 16 commits into from
Sep 4, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions conversions/hexadecimal_to_decimal
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,39 @@ def hex_to_decimal(hex_string: str) -> int:
10
>>> hex_to_decimal("")
ValueError: Empty string value was passed to the function
>>> hex_to_decimal("-12m")
>>> hex_to_decimal("12m")
ValueError: Non-hexadecimal value was passed to the function
>>> 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")
ValueError: Non-hexadecimal value was passed to the function
"""
mohammadreza490 marked this conversation as resolved.
Show resolved Hide resolved
decimal_number = 0
#https://www.programiz.com/python-programming/methods/built-in/hex
#Hex numbers start with 0x. We use [2:] to get the hex number after 0x
hex_table = {hex(i)[2:]: i for i in range(16)}
hex_string = hex_string.strip().lower()
isNegative = False
mohammadreza490 marked this conversation as resolved.
Show resolved Hide resolved
if not hex_string:
raise ValueError("Empty string value was passed to the function")
if(hex_string[0] == "-"):
mohammadreza490 marked this conversation as resolved.
Show resolved Hide resolved
isNegative = True
hex_string = hex_string[1:]
for char in hex_string:
if char not in hex_table:
raise ValueError("Non-hexadecimal value was passed to the function")
decimal_number = 16 * decimal_number + hex_table[char.upper()]
decimal_number = 16 * decimal_number + hex_table[char]
if isNegative:
decimal_number *= -1
return decimal_number


if __name__ == "__main__":
from doctest import testmod

mohammadreza490 marked this conversation as resolved.
Show resolved Hide resolved
testmod()