TheAlgorithms/Python · error · ValueError
Shift must be non-negative
Error message
Shift must be non-negative
What it means
Thrown by left_rotate_32() when the shift amount is negative. A negative rotation is undefined for the bit trick used ((i << shift) ^ (i >> (32 - shift))) and Python's arbitrary-precision ints would silently produce wrong results, so shift < 0 is rejected. Note the value guard (error 388) fires first if both are invalid.
Source
Thrown at hashes/md5.py:293
>>> left_rotate_32(4294967295, 4)
4294967295
>>> left_rotate_32(1234, 0)
1234
>>> left_rotate_32(0, 0)
0
>>> left_rotate_32(-1, 0)
Traceback (most recent call last):
...
ValueError: Input must be non-negative
>>> left_rotate_32(0, -1)
Traceback (most recent call last):
...
ValueError: Shift must be non-negative
"""
if i < 0:
raise ValueError("Input must be non-negative")
if shift < 0:
raise ValueError("Shift must be non-negative")
return ((i << shift) ^ (i >> (32 - shift))) % 2**32
def md5_me(message: bytes) -> bytes:
"""
Returns the 32-char MD5 hash of a given message.
Reference: https://en.wikipedia.org/wiki/MD5#Algorithm
Arguments:
message {[string]} -- [message]
Returns:
32-char MD5 hash string
>>> md5_me(b"")
b'd41d8cd98f00b204e9800998ecf8427e'
>>> md5_me(b"The quick brown fox jumps over the lazy dog")View on GitHub (pinned to f5988cc097)
Solutions
- Pass shifts in [0, 31] per the MD5 specification; use the fixed shift table verbatim.
- Normalize computed shifts: shift % 32.
- Validate your shift table length/contents once at module load, not per call.
Example fix
# before left_rotate_32(x, s - t) # s - t may be negative # after left_rotate_32(x, (s - t) % 32)
Defensive patterns
Strategy: validation
Validate before calling
assert 0 <= shift < 32, f"shift must be in [0, 32), got {shift}" Type guard
def is_valid_shift(shift: int) -> bool:
return isinstance(shift, int) and 0 <= shift < 32 Try / catch
try:
r = left_rotate_32(x, s)
except ValueError as e:
if "Shift" in str(e):
r = left_rotate_32(x, s % 32)
else:
raise Prevention
- Use the MD5 spec's fixed shift tables verbatim.
- Normalize computed shifts with % 32.
- Validate shift tables once at module import.
When it happens
Trigger: Calling left_rotate_32(0, -1), or computing the shift from an expression like (s - t) that can go negative, or indexing a shift table out of range with a negative index.
Common situations: Parameterized rotation schedules where the shift is derived at runtime (e.g. variable round constants) and can underflow; typos in shift tables copied from the MD5 spec.
Related errors
- Input must be of length 32
- Input must be non-negative
- Input must have length that's a multiple of 512
- 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/7e68445afd0d7f67.
Report an issue: GitHub.