|
| 1 | +def bin_to_hexadecimal(binary_str: str) -> str: |
| 2 | + """ |
| 3 | + Converting a binary string into hexadecimal using Grouping Method |
| 4 | +
|
| 5 | + >>> bin_to_hexadecimal('101011111') |
| 6 | + '0x15f' |
| 7 | + >>> bin_to_hexadecimal(' 1010 ') |
| 8 | + '0x0a' |
| 9 | + >>> bin_to_hexadecimal('-11101') |
| 10 | + '-0x1d' |
| 11 | + >>> bin_to_hexadecimal('a') |
| 12 | + Traceback (most recent call last): |
| 13 | + ... |
| 14 | + ValueError: Non-binary value was passed to the function |
| 15 | + >>> bin_to_hexadecimal('') |
| 16 | + Traceback (most recent call last): |
| 17 | + ... |
| 18 | + ValueError: Empty string was passed to the function |
| 19 | + """ |
| 20 | + BITS_TO_HEX = { |
| 21 | + "0000": "0", |
| 22 | + "0001": "1", |
| 23 | + "0010": "2", |
| 24 | + "0011": "3", |
| 25 | + "0100": "4", |
| 26 | + "0101": "5", |
| 27 | + "0110": "6", |
| 28 | + "0111": "7", |
| 29 | + "1000": "8", |
| 30 | + "1001": "9", |
| 31 | + "1010": "a", |
| 32 | + "1011": "b", |
| 33 | + "1100": "c", |
| 34 | + "1101": "d", |
| 35 | + "1110": "e", |
| 36 | + "1111": "f", |
| 37 | + } |
| 38 | + |
| 39 | + # Sanitising parameter |
| 40 | + binary_str = str(binary_str).strip() |
| 41 | + |
| 42 | + # Exceptions |
| 43 | + if not binary_str: |
| 44 | + raise ValueError("Empty string was passed to the function") |
| 45 | + is_negative = binary_str[0] == "-" |
| 46 | + binary_str = binary_str[1:] if is_negative else binary_str |
| 47 | + if not all(char in "01" for char in binary_str): |
| 48 | + raise ValueError("Non-binary value was passed to the function") |
| 49 | + |
| 50 | + binary_str = ( |
| 51 | + "0" * (4 * (divmod(len(binary_str), 4)[0] + 1) - len(binary_str)) + binary_str |
| 52 | + ) |
| 53 | + |
| 54 | + hexadecimal = [] |
| 55 | + for x in range(0, len(binary_str), 4): |
| 56 | + hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]]) |
| 57 | + hexadecimal_str = "0x" + "".join(hexadecimal) |
| 58 | + |
| 59 | + return "-" + hexadecimal_str if is_negative else hexadecimal_str |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + from doctest import testmod |
| 64 | + |
| 65 | + testmod() |
0 commit comments