Let's start with an answer to your title question.
How is overflow detected in two's complement?
Overflow rule : If two numbers with the same sign (both positive or both negative) are added, then overflow occurs if and only if the result has the opposite sign.
But you ask something different on the body of your question after your example.
So here the result has fifth left bit 10001
- is it overflow?
No! there is no overflow here. That fifth bit is the carry/borrow. Carry if you are talking about addition. Borrow if you are talking about subtraction.
Overflow occurs when the number that you trying to represent is out of the range of numbers that can be represented. In your example you are using 4-bits two's complement, that means you can represent any number in the range -8
(1000
) up to +7
(0111
). The result of your subtraction 2-1
is +1
, a number that lies within the range of representation.
When we add a negative and a positive operand, the result will always be in the range of representation. Overflows occur when we add two numbers with the same sign (both positive or both negative) and the result has the opposite sign.
Most of misunderstanding surrounding carry-out and overflow comes from the fact we use the carry-out as one of the parameters to generate overflow flag. They are strongly related but they are not the same thing.
When adding numbers in two's complement, if the carry-out and the carry-on into the most significant bit (sign bit) are different that means an overflow has occurred.
Let's see two negative operands with a positive result:
-8 + (-1) = -9
1000 (carry)
1000 (-8)
+ 1111 (-1)
------
0111 (+7) OVERFLOW!
The carry-out is 1 and the carry-on to sign bit (MSB) is 0.
And now, an example of two positive operands with a negative result.
+7 + 1 = +8
0111 (carry)
0111 (+7)
+ 0001 (+1)
------
1000 (-8) OVERFLOW!
The carry-out is 0 and the carry-on to sign bit (MSB) is 1.
-1
is given in four bits, but your answer is calculated in five bits. If you word size is 5 bits, then the value of-1
should be11111
, not1111
. In a 5-bit word,1111
is the value15
, not-1
. You calculated2 + 15 = -15
. Also, what is your programming question? (This isn't really a programming question yet.) – Raymond Chen-1
to four bits, and then added and received five bits. How should I have done it differently? – Max Koretskyi2-1
using four bits? – Max Koretskyi0001
with carry1
– M.M