Skip to content
๐Ÿ’ฅ Integer Overflow

๐Ÿ’ฅ 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โฟ โˆ’ 1 back to 0
  • In signed (2โ€™s complement) systems: values wrap from +2โฟโปยน โˆ’ 1 to โˆ’2โฟโปยน

๐Ÿงฎ Example: 4-bit Signed Overflow

ABA + BExpectedActualInterpretation
0111 (+7)0001 (+1)1000+8โˆ’8Overflow 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 modulus 2โด = 16)

โŒ Hardware View

  • 4-bit signed integers range from โˆ’8 to +7
  • 1000 is 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_MSB

Where:

  • C_in_MSB: carry into most significant bit
  • C_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 โˆ’1
Last updated on