Two’s Complement, Carry, and Signed Overflow

Interpret a fixed-width sum in signed and unsigned models and identify why carry and signed overflow report different conditions.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. The bit pattern permits two interpretations
  2. The flags answer different questions

The bit pattern permits two interpretations

For width \(w\), an unsigned pattern has value \(u\) between zero and \(2^w-1\). In two’s complement, the same pattern denotes \(u\) below \(2^{w-1}\) and \(u-2^w\) otherwise. Addition of the bit patterns computes the same residue modulo \(2^w\). The program’s signed interpretation determines whether the mathematical result fits the signed range.

The flags answer different questions

For four bits, \(0111+0001=1000\). Unsigned, the result is eight with no carry out. Signed, seven plus one exceeds the maximum of seven and the pattern denotes negative eight. Conversely \(1111+0001=0000\) with a carry is signed negative one plus one, which fits. Instruction set semantics say which results or flags a machine provides. Compiler arithmetic must preserve the source rules for overflow and defined behavior.[1][2]

References

  1. RISC-V International, The RISC-V Instruction Set Manual: Unprivileged Architecture ↩
  2. MIT OpenCourseWare, Computation Structures ↩