TheAlgorithms/Python · error · ValueError
Non-binary value was passed to the function
Error message
Non-binary value was passed to the function
What it means
bin_to_hexadecimal raises this ValueError when any character of the input (after an optional leading '-' is removed) is not '0' or '1'. The function then left-pads to a multiple of 4 bits and maps each nibble via a lookup dict, so non-binary characters would cause a KeyError later; validation happens first.
Source
Thrown at conversions/binary_to_hexadecimal.py:49
>>> bin_to_hexadecimal('a')
Traceback (most recent call last):
...
ValueError: Non-binary value was passed to the function
>>> bin_to_hexadecimal('')
Traceback (most recent call last):
...
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 __name__ == "__main__":
from doctest import testmod
testmod()
View on GitHub (pinned to f5988cc097)
Solutions
- Strip '0b' prefix first: bin_to_hexadecimal(bin_str.removeprefix('0b'))
- Validate with a regex before calling: re.fullmatch(r'-?[01]+', s)
- If the input is decimal, use a decimal-to-hex path (hex(int(s))) instead
Example fix
# before
bin_to_hexadecimal(bin(255))
# ValueError: Non-binary value was passed to the function
# after
bin_to_hexadecimal(bin(255).removeprefix('0b'))
# '0xff' Defensive patterns
Strategy: validation
Validate before calling
import re
s = str(binary_str).strip()
assert re.fullmatch(r'-?[01]+', s), f'not binary: {binary_str!r}'
bin_to_hexadecimal(s) Type guard
def is_binary_string(s) -> bool:
s = str(s).strip().removeprefix('-')
return s != '' and all(c in '01' for c in s) Try / catch
try:
bin_to_hexadecimal(s)
except ValueError as e:
if 'Non-binary' in str(e):
raise ValueError('expected binary digits only') from e
raise Prevention
- removeprefix('0b') on bin() output
- Route hex/decimal inputs to their own converters
- Regex-validate at the parsing layer
When it happens
Trigger: bin_to_hexadecimal('0x1F') (hex input to a binary function), bin_to_hexadecimal('10 2'), bin_to_hexadecimal(bin(255)) because the '0b' prefix contains 'b', bin_to_hexadecimal('1.01').
Common situations: Wrong-direction conversion (already-hex or decimal strings passed in); passing Python's bin() output without stripping '0b'; locale/typo digit corruption.
Related errors
- Empty string was passed to the function
- Non-binary value was passed to the function
- Empty string was passed to the function
- Non-binary value was passed to the function
- Invalid 'from_type' value: {from_type!r}.\nConversion abbrev
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/91f3f8420862c054.
Report an issue: GitHub.