Signed Integers and Flags (Two’s Complement)

From MediaWiki
Jump to navigation Jump to search

Signed Integers and Flags (Two’s Complement)

This page explains how signed integers are represented in x86 architecture using two’s complement and how arithmetic instructions affect CPU flags.

Unsigned vs signed integers

Unsigned integers represent only positive values. Signed integers represent both positive and negative values using two’s complement.

Example with 8 bits:

  • 00000000₂ = 0
  • 00000001₂ = +1
  • 01111111₂ = +127
  • 11111111₂ = −1
  • 11111110₂ = −2
  • 10000000₂ = −128

In two’s complement, the most significant bit (MSB) is the sign bit:

  • 0 = positive
  • 1 = negative

How two’s complement works

To negate a binary number: 1. Invert all bits. 2. Add 1 to the result.

Example: Convert +5 (00000101₂) to −5:

Invert → 11111010₂  
Add 1  → 11111011₂ = −5

Overflow and wrapping

When signed arithmetic exceeds the representable range, it wraps around and sets the overflow flag (OF).

Example:

mov eax, 0x7FFFFFFF   ; largest positive 32-bit signed number
inc eax               ; eax becomes 0x80000000 (−2147483648)
; Overflow occurs, OF = 1, SF = 1 (sign bit set)

Decrementing below the smallest value (e.g., −128 for 8-bit) wraps around to the largest positive value.

Example: continuous decrement

mov eax, 0

loop2:

dec eax
jmp loop2

EAX changes as follows:

0x00000000 → 0xFFFFFFFF (−1)
→ 0xFFFFFFFE (−2)
→ 0xFFFFFFFD (−3)

and so on.

Flags relevant for signed arithmetic

  • SF (Sign Flag): set when result is negative (MSB = 1)
  • ZF (Zero Flag): set when result is zero
  • OF (Overflow Flag): set when signed overflow occurs
  • CF (Carry Flag): used for unsigned overflow, not sign interpretation

Summary

  • Two’s complement represents negative numbers naturally.
  • Arithmetic wraps around automatically.
  • Signed overflow is detected via the Overflow Flag (OF).
  • Understanding these flags is essential for conditional branching and comparisons.