Computer Systems: Overflow and Integer Arithmetic

Unsigned and Signed Integers

  • Unsigned vs. Signed Integers:
    • Both unsigned and two's complement signed integers increment and decrement similarly.
    • They 'wrap around' at different points when reaching their limits.
    • Addition can be performed identically for both.

Binary Addition Rules

  • Binary Addition Basics:
    • 0 + 0 = 0
    • 0 + 1 = 1
    • 1 + 0 = 1
    • 1 + 1 = 10 (carry 1)
    • 1 + 1 + 1 = 11 (carry 1 again)
  • Examples demonstrate adding binary numbers together, reinforcing the same addition rules.

Understanding Overflow

  • Definition of Overflow:
    • An error that occurs when the calculated result exceeds the maximum value that can be represented within the allocated space.

Unsigned Overflow

  • What is Unsigned Overflow?:
    • Occurs when the sum exceeds the maximum possible value for the unsigned number representation.
  • Example Scenario:
    • Given two 8-bit unsigned integers, analyze the scenario where decimals are added.
    • As shown, for specific binary representations, if their sum exceeds the max value (255 for 8 bits), overflow occurs.
    • Calculation steps help identify the maximum numbers that can be added without causing an overflow.

Checking for Unsigned Overflow in MIPS

  • Instructions:
    • addu $s0, $a0, $a1 to add values without considering potential overflow.
    • Overflow detection logic compares values to UINT_MAX.

Unsigned Subtraction and Overflow

  • Subtraction:
    • Overflow occurs if the first operand is less than the second operand when subtracting.

Signed Overflow

  • Definition:
    • Signed overflow occurs when the result of a calculation exceeds the maximum positive value or goes below the minimum negative value allowed in signed representation (e.g., two's complement).
  • Example:
    • When adding two signed integers, scenarios are analyzed to determine if overflow will occur (e.g., negative + positive situations).
  • Overflow Detection:
    • Occurs if both operands have the same sign and the result has the opposite sign.
    • Testing logic for overflow can be demonstrated via MIPS assembly instructions.

MIPS Instructions for Addition and Subtraction

  • Differences between signed and unsigned operations:
    • add $v0, $a0, $a1: Performs signed add and can trigger an overflow exception
    • addu $v0, $a0, $a1: Performs unsigned add without causing an overflow exception.
  • Similar logic applies for subtraction where signed and unsigned operations differ mainly in overflow handling.

Handling Overflow in Compilers

  • Various methods include:
    • Doing nothing, relying on default behavior (like C language).
    • Adding extra instructions to check for overflow before operations occur.
    • Writing exception handlers to manage overflow when it happens.
  • Other ISAs may use an overflow flag to indicate if an overflow occurred during operations.