### Python - Convert Binary to Hexadecimal Example

In this source code example, we will write a code to convert a binary value to its hexadecimal equivalent in Python.

# Python - Convert Binary to Hexadecimal Example

``````def bin_to_hexadecimal(binary_str: str) -> str:

BITS_TO_HEX = {
"0000": "0",
"0001": "1",
"0010": "2",
"0011": "3",
"0100": "4",
"0101": "5",
"0110": "6",
"0111": "7",
"1000": "8",
"1001": "9",
"1010": "a",
"1011": "b",
"1100": "c",
"1101": "d",
"1110": "e",
"1111": "f",
}

# Sanitising parameter
binary_str = str(binary_str).strip()

# Exceptions
if not binary_str:
raise ValueError("Empty string was passed to the function")
is_negative = binary_str == "-"
binary_str = binary_str[1:] if is_negative else binary_str
if not all(char in "01" for char in binary_str):
raise ValueError("Non-binary value was passed to the function")

binary_str = (
"0" * (4 * (divmod(len(binary_str), 4) + 1) - len(binary_str)) + binary_str
)

for x in range(0, len(binary_str), 4):

if __name__ == "__main__":

# Converting a binary string into hexadecimal using Grouping Method
``````0x15f