Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 10 additions & 36 deletions conversions/binary_to_hexadecimal.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,11 @@
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",
}


def bin_to_hexadecimal(binary_str: str) -> str:
"""
Converting a binary string into hexadecimal using Grouping Method
Convert a binary string to hexadecimal.
Comment thread
Ewanjohndennis marked this conversation as resolved.

>>> bin_to_hexadecimal('101011111')
'0x15f'
>>> bin_to_hexadecimal(' 1010 ')
'0x0a'
'0xa'
>>> bin_to_hexadecimal('-11101')
'-0x1d'
>>> bin_to_hexadecimal('a')
Expand All @@ -37,27 +17,21 @@ def bin_to_hexadecimal(binary_str: str) -> str:
...
ValueError: Empty string was passed to the function
"""
# 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[0] == "-"
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)[0] + 1) - len(binary_str)) + binary_str
)

hexadecimal = []
for x in range(0, len(binary_str), 4):
hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]])
hexadecimal_str = "0x" + "".join(hexadecimal)

return "-" + hexadecimal_str if is_negative else hexadecimal_str
if not binary_str or not all(char in "01" for char in binary_str):
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merging the empty string check and non-binary check into one condition
is cleaner than the old two-step approach. One thing to note: when
binary_str becomes empty after stripping the "-" sign on a negative
input like "-", this combined check will raise "Non-binary value was
passed to the function" instead of "Empty string was passed to the
function" — the error message may be misleading in that edge case.

Consider checking for empty string separately after stripping the sign.

raise ValueError("Non-binary value was passed to the function")
# Uses built-in int() for binary parsing and hex() for conversion
hex_str = "0x" + hex(int(binary_str, 2))[2:]
Comment thread
Ewanjohndennis marked this conversation as resolved.
if hex_str == "0x0":
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This edge case handling for "0x0" resetting is_negative to False is
a good catch — negative zero (-0) is not meaningful in hex. However
this logic is a bit hidden. A brief inline comment would help readers
understand why:

-0 is not a valid representation, treat as positive zero

if hex_str == "0x0":
is_negative = False

is_negative = False
return "-" + hex_str if is_negative else hex_str


if __name__ == "__main__":
Expand Down