From 1385e47c36f9f5af75c1127bcafe61725a390895 Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Fri, 4 Sep 2020 14:48:44 +0100 Subject: [PATCH] Create hexadecimal_to_decimal (#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 * 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 * 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 * Update conversions/hexadecimal_to_decimal Co-authored-by: Christian Clauss * Update hexadecimal_to_decimal * Update hexadecimal_to_decimal Co-authored-by: Tapajyoti Bose <44058757+ruppysuppy@users.noreply.github.com> Co-authored-by: Christian Clauss --- conversions/hexadecimal_to_decimal | 45 ++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 conversions/hexadecimal_to_decimal diff --git a/conversions/hexadecimal_to_decimal b/conversions/hexadecimal_to_decimal new file mode 100644 index 000000000..e87caa0f4 --- /dev/null +++ b/conversions/hexadecimal_to_decimal @@ -0,0 +1,45 @@ +hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x' + + +def hex_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") + ValueError: Non-hexadecimal value was passed to the function + >>> hex_to_decimal("") + ValueError: Empty string value was passed to the function + >>> hex_to_decimal("12m") + ValueError: Non-hexadecimal value was passed to the function + """ + hex_string = hex_string.strip().lower() + if not hex_string: + raise ValueError("Empty string was passed to the function") + is_negative = hex_string[0] == "-" + if is_negative: + hex_string = hex_string[1:] + if not all(char in hex_table for char in hex_string): + raise ValueError("Non-hexadecimal value was passed to the function") + decimal_number = 0 + for char in hex_string: + decimal_number = 16 * decimal_number + hex_table[char] + if is_negative: + decimal_number = -decimal_number + return decimal_number + + +if __name__ == "__main__": + from doctest import testmod + + testmod()