Skip to content

Simplify bin_to_hexadecimal function#14570

Open
Ewanjohndennis wants to merge 2 commits intoTheAlgorithms:masterfrom
Ewanjohndennis:patch-2
Open

Simplify bin_to_hexadecimal function#14570
Ewanjohndennis wants to merge 2 commits intoTheAlgorithms:masterfrom
Ewanjohndennis:patch-2

Conversation

@Ewanjohndennis
Copy link
Copy Markdown

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.

Describe your change:

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Checklist:

Ewanjohndennis and others added 2 commits April 21, 2026 10:03
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.
@algorithms-keeper algorithms-keeper Bot added awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files labels Apr 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant