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 3 commits
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
46 changes: 46 additions & 0 deletions conversions/hexadecimal_to_decimal
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
def hex_to_decimal(hex_string: str) -> int:
"""
converts a given hexadecimal value to its decimal value
>>> hexToDecimal("a")
10
>>> hexToDecimal("")
ValueError: Empty string value was passed to the function
>>> hexToDecimal("-12m")
ValueError: None hexadecimal value was passed to the function
mohammadreza490 marked this conversation as resolved.
Show resolved Hide resolved
>>> hexToDecimal("12f")
303
>>> hexToDecimal(" 12f ")
303
"""
mohammadreza490 marked this conversation as resolved.
Show resolved Hide resolved
decimal_number = 0
hex_table = {
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"A": 10,
"B": 11,
"C": 12,
"D": 13,
"E": 14,
"F": 15,
}
mohammadreza490 marked this conversation as resolved.
Show resolved Hide resolved
hex_string = hex_string.strip()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
hex_string = hex_string.strip()
hex_string = hex_string.strip().lower()

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do this once on the entire str instead of doing it on each character.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please do not mark this resolved if you have converted the entire string instead of converting it a character at a time.

if not hex_string:
raise ValueError("Invalid Hexadecimal Input")
for char in hex_string:
if char.upper() not in hex_table:
raise ValueError("Invalid Hexadecimal Input")
decimal_number = 16 * decimal_number + hex_table[char.upper()]
return decimal_number


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

testmod()