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
- Mask values to unsigned 32-bit before formatting: reformat_hex(value & 0xFFFFFFFF).
- Replace a - b with (a - b) % 2**32 in any 32-bit arithmetic feeding this function.
- 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
- Wrap every 32-bit add/sub with % 2**32 in custom crypto math.
- Parse binary words as unsigned (struct '<I').
- Mask at the boundary: value & 0xFFFFFFFF.
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
- Input must be of length 32
- Input must have length that's a multiple of 512
- Shift must be non-negative
- number must be positive
- The value of input must be non-negative
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/8c6c3caa79789ece.
Report an issue: GitHub.