Overflow Detection in Integer Arithmetic
You'll learn: How to recognize when an arithmetic operation produces a result too large (or too small) to fit in the available bits, and how hardware catches these errors.
What Is Overflow?
When you add, subtract, or multiply integers in hardware, the result might need more bits than your register can hold. This is overflow—like trying to pour a gallon of water into a cup. With fixed-width representations (8-bit, 32-bit, etc.), overflow means the computed value exceeds the representable range and wraps around incorrectly.
For example, in 8-bit two's complement (range: -128 to +127), adding 100 + 50 = 150 produces a bit pattern that hardware interprets as -106 instead.
How Hardware Detects Overflow
Unsigned Addition
Overflow occurs if the true sum exceeds the maximum representable value. Hardware sets a carry flag when the most significant bit produces a carry-out during addition.
Signed Addition (Two's Complement)
Overflow occurs when:
- Two positive numbers sum to a negative result, OR
- Two negative numbers sum to a positive result
The rule: Overflow happens if the carry into the sign bit differs from the carry out of the sign bit. Hardware sets an overflow flag to signal this.
Example
Adding 01111111 (+127) and 00000001 (+1) in 8-bit:
- Result:
10000000(interpreted as -128) - Sign bit flipped unexpectedly → overflow detected
Why It Matters
Without overflow detection, programs silently produce wrong answers. Languages like C ignore overflow by default, but safety-critical systems (avionics, medical devices) must check overflow flags or use larger data types.
Key Takeaway: Overflow occurs when arithmetic results exceed the representable range; hardware uses carry and overflow flags to signal when this happens, allowing software to detect and handle errors.