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
(hex_num: str)
| 1 | def hex_to_bin(hex_num: str) -> int: |
| 2 | """ |
| 3 | Convert a hexadecimal value to its binary equivalent |
| 4 | #https://stackoverflow.com/questions/1425493/convert-hex-to-binary |
| 5 | Here, we have used the bitwise right shift operator: >> |
| 6 | Shifts the bits of the number to the right and fills 0 on voids left as a result. |
| 7 | Similar effect as of dividing the number with some power of two. |
| 8 | Example: |
| 9 | a = 10 |
| 10 | a >> 1 = 5 |
| 11 | |
| 12 | >>> hex_to_bin("AC") |
| 13 | 10101100 |
| 14 | >>> hex_to_bin("9A4") |
| 15 | 100110100100 |
| 16 | >>> hex_to_bin(" 12f ") |
| 17 | 100101111 |
| 18 | >>> hex_to_bin("FfFf") |
| 19 | 1111111111111111 |
| 20 | >>> hex_to_bin("-fFfF") |
| 21 | -1111111111111111 |
| 22 | >>> hex_to_bin("F-f") |
| 23 | Traceback (most recent call last): |
| 24 | ... |
| 25 | ValueError: Invalid value was passed to the function |
| 26 | >>> hex_to_bin("") |
| 27 | Traceback (most recent call last): |
| 28 | ... |
| 29 | ValueError: No value was passed to the function |
| 30 | """ |
| 31 | |
| 32 | hex_num = hex_num.strip() |
| 33 | if not hex_num: |
| 34 | raise ValueError("No value was passed to the function") |
| 35 | |
| 36 | is_negative = hex_num[0] == "-" |
| 37 | if is_negative: |
| 38 | hex_num = hex_num[1:] |
| 39 | |
| 40 | try: |
| 41 | int_num = int(hex_num, 16) |
| 42 | except ValueError: |
| 43 | raise ValueError("Invalid value was passed to the function") |
| 44 | |
| 45 | bin_str = "" |
| 46 | while int_num > 0: |
| 47 | bin_str = str(int_num % 2) + bin_str |
| 48 | int_num >>= 1 |
| 49 | |
| 50 | return int(("-" + bin_str) if is_negative else bin_str) |
| 51 | |
| 52 | |
| 53 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected