{"record":{"id":"91f3f8420862c054","repo":"TheAlgorithms/Python","slug":"non-binary-value-was-passed-to-the-function-91f3f8","errorCode":null,"errorMessage":"Non-binary value was passed to the function","messagePattern":"Non-binary value was passed to the function","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"conversions/binary_to_hexadecimal.py","lineNumber":49,"sourceCode":"    >>> bin_to_hexadecimal('a')\n    Traceback (most recent call last):\n        ...\n    ValueError: Non-binary value was passed to the function\n    >>> bin_to_hexadecimal('')\n    Traceback (most recent call last):\n        ...\n    ValueError: Empty string was passed to the function\n    \"\"\"\n    # Sanitising parameter\n    binary_str = str(binary_str).strip()\n\n    # Exceptions\n    if not binary_str:\n        raise ValueError(\"Empty string was passed to the function\")\n    is_negative = binary_str[0] == \"-\"\n    binary_str = binary_str[1:] if is_negative else binary_str\n    if not all(char in \"01\" for char in binary_str):\n        raise ValueError(\"Non-binary value was passed to the function\")\n\n    binary_str = (\n        \"0\" * (4 * (divmod(len(binary_str), 4)[0] + 1) - len(binary_str)) + binary_str\n    )\n\n    hexadecimal = []\n    for x in range(0, len(binary_str), 4):\n        hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]])\n    hexadecimal_str = \"0x\" + \"\".join(hexadecimal)\n\n    return \"-\" + hexadecimal_str if is_negative else hexadecimal_str\n\n\nif __name__ == \"__main__\":\n    from doctest import testmod\n\n    testmod()\n","sourceCodeStart":31,"sourceCodeEnd":67,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/conversions/binary_to_hexadecimal.py#L31-L67","documentation":"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.","triggerScenarios":"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').","commonSituations":"Wrong-direction conversion (already-hex or decimal strings passed in); passing Python's bin() output without stripping '0b'; locale/typo digit corruption.","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"],"exampleFix":"# before\nbin_to_hexadecimal(bin(255))\n# ValueError: Non-binary value was passed to the function\n\n# after\nbin_to_hexadecimal(bin(255).removeprefix('0b'))\n# '0xff'","handlingStrategy":"validation","validationCode":"import re\ns = str(binary_str).strip()\nassert re.fullmatch(r'-?[01]+', s), f'not binary: {binary_str!r}'\nbin_to_hexadecimal(s)","typeGuard":"def is_binary_string(s) -> bool:\n    s = str(s).strip().removeprefix('-')\n    return s != '' and all(c in '01' for c in s)","tryCatchPattern":"try:\n    bin_to_hexadecimal(s)\nexcept ValueError as e:\n    if 'Non-binary' in str(e):\n        raise ValueError('expected binary digits only') from e\n    raise","preventionTips":["removeprefix('0b') on bin() output","Route hex/decimal inputs to their own converters","Regex-validate at the parsing layer"],"tags":["conversions","binary","hexadecimal","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}