From 368ce7aecc2acd5d3b472dc9141d160d98164353 Mon Sep 17 00:00:00 2001 From: TANMAY SRIVASTAVA <77936821+ktsrivastava29@users.noreply.github.com> Date: Thu, 20 May 2021 13:58:00 +0530 Subject: [PATCH] Added a hex-bin.py file in conversion.py (#4433) * Added a file that converts hexa to binary * Added file to convert hexadecimal to binary * Update hex-bin.py * added type hint in the code * Added doctest * Added code to handle exception * Resolved doctest issue * Update hex-bin.py * Modified convert function * Added WhiteSpace around operators. * Made more pythonic * removed whitespace * Updated doctest command * Removed whitespace * imported union * Replaced flag with is_negative * updated return type * removed pip command * Resolved doctest issue * Resolved doctest error * Reformated the code * Changes function name * Changed exception handling statements * Update and rename hex-bin.py to hex_to_bin.py * Update newton_method.py * Update matrix_operation.py * Update can_string_be_rearranged_as_palindrome.py * Update hex_to_bin.py Co-authored-by: Christian Clauss --- conversions/hex_to_bin.py | 56 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 conversions/hex_to_bin.py diff --git a/conversions/hex_to_bin.py b/conversions/hex_to_bin.py new file mode 100644 index 000000000..e358d810b --- /dev/null +++ b/conversions/hex_to_bin.py @@ -0,0 +1,56 @@ +def hex_to_bin(hex_num: str) -> int: + """ + Convert a hexadecimal value to its binary equivalent + #https://stackoverflow.com/questions/1425493/convert-hex-to-binary + Here, we have used the bitwise right shift operator: >> + Shifts the bits of the number to the right and fills 0 on voids left as a result. + Similar effect as of dividing the number with some power of two. + Example: + a = 10 + a >> 1 = 5 + + >>> hex_to_bin("AC") + 10101100 + >>> hex_to_bin("9A4") + 100110100100 + >>> hex_to_bin(" 12f ") + 100101111 + >>> hex_to_bin("FfFf") + 1111111111111111 + >>> hex_to_bin("-fFfF") + -1111111111111111 + >>> hex_to_bin("F-f") + Traceback (most recent call last): + ... + ValueError: Invalid value was passed to the function + >>> hex_to_bin("") + Traceback (most recent call last): + ... + ValueError: No value was passed to the function + """ + + hex_num = hex_num.strip() + if not hex_num: + raise ValueError("No value was passed to the function") + + is_negative = hex_num[0] == "-" + if is_negative: + hex_num = hex_num[1:] + + try: + int_num = int(hex_num, 16) + except ValueError: + raise ValueError("Invalid value was passed to the function") + + bin_str = "" + while int_num > 0: + bin_str = str(int_num % 2) + bin_str + int_num >>= 1 + + return int(("-" + bin_str) if is_negative else bin_str) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()