TheAlgorithms/Python · error · ValueError

Input must be non-negative

Error message

Input must be non-negative

What it means

Thrown by reformat_hex() in the MD5 implementation when asked to format a negative integer. The function formats i as 8 hex digits (mod 2**32) and byte-swaps them for little-endian output; negative values have no such representation, so they are rejected with ValueError.

Source

Thrown at hashes/md5.py:81

        8-char little-endian hex string

    >>> reformat_hex(1234)
    b'd2040000'
    >>> reformat_hex(666)
    b'9a020000'
    >>> reformat_hex(0)
    b'00000000'
    >>> reformat_hex(1234567890)
    b'd2029649'
    >>> reformat_hex(1234567890987654321)
    b'b11c6cb1'
    >>> reformat_hex(-1)
    Traceback (most recent call last):
    ...
    ValueError: Input must be non-negative
    """
    if i < 0:
        raise ValueError("Input must be non-negative")

    hex_rep = format(i, "08x")[-8:]
    little_endian_hex = b""
    for j in [3, 2, 1, 0]:
        little_endian_hex += hex_rep[2 * j : 2 * j + 2].encode("utf-8")
    return little_endian_hex


def preprocess(message: bytes) -> bytes:
    """
    Preprocesses the message string:
    - Convert message to bit string
    - Pad bit string to a multiple of 512 chars:
        - Append a 1
        - Append 0's until length = 448 (mod 512)
        - Append length of original message (64 chars)

    Example: Suppose the input is the following:

View on GitHub (pinned to f5988cc097)

Solutions

  1. Mask values to unsigned 32-bit before formatting: reformat_hex(value & 0xFFFFFFFF).
  2. Replace a - b with (a - b) % 2**32 in any 32-bit arithmetic feeding this function.
  3. Parse binary words with signed=False / '<I' format so negatives never appear.

Example fix

# before
reformat_hex(a - b)  # can be negative

# after
reformat_hex((a - b) % 2**32)
Defensive patterns

Strategy: validation

Validate before calling

value &= 0xFFFFFFFF  # force unsigned 32-bit before calling

Type guard

def is_u32(i: int) -> bool:
    return isinstance(i, int) and 0 <= i < 2**32

Try / catch

try:
    hx = reformat_hex(i)
except ValueError:
    hx = reformat_hex(i % 2**32)  # wrap into 32-bit range

Prevention

When it happens

Trigger: Calling reformat_hex(-1), or passing an accumulator/word that went negative because of a subtraction (e.g. computing a - b on 32-bit words without wrapping).

Common situations: Reimplementing MD5 round math where subtractions produce negatives; feeding signed parse results (e.g. from a struct with signed interpretation) into a routine that expects unsigned 32-bit words.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/8c6c3caa79789ece. Report an issue: GitHub.