๐ฅ Integer Overflow
๐ง Motivation
โน๏ธ
Why we care Integer overflow is a semantic mismatch between mathematical expectation and hardware constraints.
In modular arithmetic, overflow is benign. In fixed-width binary systems, it can flip signs, corrupt logic, or cause unintended wraparound.
๐ฃ What Is Integer Overflow?
Integer overflow occurs when the result of an arithmetic operation exceeds the maximum value representable within a fixed number of bits.
- In unsigned systems: values wrap from
2โฟ โ 1back to0 - In signed (2โs complement) systems: values wrap from
+2โฟโปยน โ 1toโ2โฟโปยน
๐งฎ Example: 4-bit Signed Overflow
| A | B | A + B | Expected | Actual | Interpretation |
|---|---|---|---|---|---|
0111 (+7) | 0001 (+1) | 1000 | +8 | โ8 | Overflow occurred |
MSB flipped โ system interprets result as negative
๐ Why It Happens
โ Mathematical View
- You expect:
7 + 1 = 8 - In modular arithmetic:
8 mod 16 = 8โโ (still valid within modulus2โด = 16)
โ Hardware View
- 4-bit signed integers range from
โ8 to +7 1000is interpreted asโ8- Result is semantically incorrect, even if bitwise correct
โ ๏ธ Overflow Detection Logic
๐ง Signed Addition Overflow
Occurs when:
- Adding two positive numbers yields a negative result
- Adding two negative numbers yields a positive result
๐ง Detection Formula
Overflow = C_in_MSB โ C_out_MSBWhere:
C_in_MSB: carry into most significant bitC_out_MSB: carry out from most significant bit
๐ Visual Anchor: 4-bit Signed Wraparound
+7 โ 0111 +8 โ 1000 โ interpreted as โ8
+9 โ 1001 โ interpreted as โ7
...
+15 โ 1111 โ interpreted as โ1Last updated on