2s complement.
Issues of overflow and carry. (Using an 8-bit signed number storage).
01111111 127
+ 00000001 1
--------
10000000 128 (unsigned) or -128 (signed and wrong)
Overflow - when the result is larger than the storage unit.
(like carry for unsigned values).
Overflow occurs when operands have same sign but sum has opposite sign.
No Overflow, operands have different signs
-1 + 127
1111 1111 -1
+ 0111 1111 127
----------
1 0lll lll0 126
signs of operands don't match - good result.
# The carry flag will be set. The programmer chooses to ignore.
No Overflow, operands have same sign but so does sum.
Possible overflow.
Sign bits match - good result. carry set. The carry is ignored.
-1 + -1
1111 1111 -1
+ 1111 1111 -1
----------
1 1111 1110 -2
Overflow occurs, signs match but result has different sign.
-127 + -3 0111 1111 127 0000 0011 3 (absolute value)
1000 0000 1111 1100 flip
1000 0001 1 1 add 1
+ 1111 1101 1000 0001 1111 1101 2's complement
----------
1 0111 1110
^
Sign change
Overflow flag set.
0111 1110 = 126 Should be -130
Similarly, two positives with a sum > 127 would create a sum with the
high bit set or a negative number.
Most CPUs implement an overflow flag for this.
Along with firmware routines for handling.
Intel x86 - INTO (interrupt if overflow)
Signed and unsigned storage is flagged by CPU but user chooses how to
process results with appropriate code.
Overview