Integer Overflow & Bit-Pattern Interpretation (Signed vs Unsigned)
Integer Overflow & Bit-Pattern Interpretation (Signed vs Unsigned)
This page explains integer overflow, how bit patterns can represent different values depending on interpretation, and why signed and unsigned integers share the same arithmetic operations.
Integer overflow
An integer has a fixed number of bits. When an arithmetic operation exceeds the largest representable value, it wraps around to the smallest one. This is called overflow.
Example with 8-bit unsigned values: 11111111₂ (255) + 00000001₂ (1) = 00000000₂ (0)
Overflow behaves like a clock: after 23:59, the next minute is 00:00 again.
Example with 8-bit signed values: 01111111₂ (+127) + 00000001₂ = 10000000₂ (−128)
Overflow in signed integers can flip the sign of the result.
Bit pattern interpretation
The same binary sequence can represent a different value depending on the interpretation.
Pattern | Unsigned | Signed (two’s complement)
-------- | -------- | --------------------------
00000000 | 0 | 0
01111111 | 127 | 127
10000000 | 128 | −128
11111111 | 255 | −1
The CPU does not distinguish between signed and unsigned numbers. Only the data type chosen by the programmer determines how the bit pattern is interpreted.
Unified arithmetic
Addition and subtraction work the same for both signed and unsigned integers. The operation is purely bitwise; interpretation changes meaning.
Example (8-bit): 00000101₂ (5) + 11111101₂ (−3) = 1 00000010₂ → ignoring carry gives 00000010₂ (2)
The same logic also applies to unsigned arithmetic: 5 + 253 = 258 → wraps to 2.
Detecting overflow
Unsigned overflow: Occurs when a carry goes beyond the most significant bit.
Signed overflow: Occurs when two operands with the same sign produce a result with a different sign.
Example:
- 01111111₂ (127) + 00000001₂ (1) = 10000000₂ (−128) → overflow.
- 11111111₂ (−1) + 11111111₂ (−1) = 11111110₂ (−2) → no overflow.
Why overflow matters
- In low-level languages like C, overflow of unsigned integers is well-defined and wraps around.
- Signed overflow is undefined behavior — results depend on compiler or CPU architecture.
- In high-level languages, some implementations detect and signal overflow (e.g., Java throws an exception).
Practical advice
- Choose signed integers when negative values are possible.
- Use unsigned integers for quantities that cannot be negative, like memory addresses or counters.
- Be aware of range limits to prevent overflow bugs.