Simplify bin_to_hexadecimal function#14570
Simplify bin_to_hexadecimal function#14570Ewanjohndennis wants to merge 4 commits intoTheAlgorithms:masterfrom
Conversation
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.
for more information, see https://pre-commit.ci
Added comment to clarify the use of built-in functions for conversion.
| 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:] | ||
| if hex_str == "0x0": |
There was a problem hiding this comment.
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
| 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): |
There was a problem hiding this comment.
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.
Rewrote
bin_to_hexadecimalto use Python's built-inint(s, 2)andhex()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 unhelpfulValueErrorabout non-binary values.Describe your change:
Checklist: