Converting a binary string into hexadecimal using Grouping Method >>> bin_to_hexadecimal('101011111') '0x15f' >>> bin_to_hexadecimal(' 1010 ') '0x0a' >>> bin_to_hexadecimal('-11101') '-0x1d' >>> bin_to_hexadecimal('a') Traceback (most recent call last):
(binary_str: str)
| 19 | |
| 20 | |
| 21 | def bin_to_hexadecimal(binary_str: str) -> str: |
| 22 | """ |
| 23 | Converting a binary string into hexadecimal using Grouping Method |
| 24 | |
| 25 | >>> bin_to_hexadecimal('101011111') |
| 26 | '0x15f' |
| 27 | >>> bin_to_hexadecimal(' 1010 ') |
| 28 | '0x0a' |
| 29 | >>> bin_to_hexadecimal('-11101') |
| 30 | '-0x1d' |
| 31 | >>> bin_to_hexadecimal('a') |
| 32 | Traceback (most recent call last): |
| 33 | ... |
| 34 | ValueError: Non-binary value was passed to the function |
| 35 | >>> bin_to_hexadecimal('') |
| 36 | Traceback (most recent call last): |
| 37 | ... |
| 38 | ValueError: Empty string was passed to the function |
| 39 | """ |
| 40 | # Sanitising parameter |
| 41 | binary_str = str(binary_str).strip() |
| 42 | |
| 43 | # Exceptions |
| 44 | if not binary_str: |
| 45 | raise ValueError("Empty string was passed to the function") |
| 46 | is_negative = binary_str[0] == "-" |
| 47 | binary_str = binary_str[1:] if is_negative else binary_str |
| 48 | if not all(char in "01" for char in binary_str): |
| 49 | raise ValueError("Non-binary value was passed to the function") |
| 50 | |
| 51 | binary_str = ( |
| 52 | "0" * (4 * (divmod(len(binary_str), 4)[0] + 1) - len(binary_str)) + binary_str |
| 53 | ) |
| 54 | |
| 55 | hexadecimal = [] |
| 56 | for x in range(0, len(binary_str), 4): |
| 57 | hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]]) |
| 58 | hexadecimal_str = "0x" + "".join(hexadecimal) |
| 59 | |
| 60 | return "-" + hexadecimal_str if is_negative else hexadecimal_str |
| 61 | |
| 62 | |
| 63 | if __name__ == "__main__": |