22

I have the next code:

mov al, -5
add al, 132
add al, 1

As I check it, the overflow flag and the carry flag will set in the first operation, and in the second, only the overflow will set.

But I don't understand why:

  1. In unsigned number, the result is 143 (8FH), and for that is fit 8-bit unsigned number (is smaller than 255) => the carry flag shouldn't be set. In signed number, the result is 127, It's fit to 8-bit signed, and the overflow shouldn't be set.

Whats wrong? Thanks.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Tom O
  • 237
  • 1
  • 4
  • 7
  • See Understanding Carry vs. Overflow conditions/flags, http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt – Peter Cordes Sep 13 '20 at 17:32

2 Answers2

32

Overflow occurs when the result of adding two positive numbers is negative or the result of adding two negative numbers is positive. For instance: +127+1=?

+127=0111 1111
  +1=0000 0001
     ---------
     1000 0000 

As we look at the sign bits of the two operands and the sign bit of the result, we find out that Overflow occurred and the answer is incorrect.

chris
  • 36,115
  • 52
  • 143
  • 252
Hassan
  • 321
  • 3
  • 2
  • The V flag also turns to 1 when we add two negative and the result is 0. If we `adds r0, r1, r0`, where `r0 = 0x80000000`, `r1 = 0x80000000`, after execution, `Z = 1`, `C = 1`, `V = 1` – Simon Z. Apr 01 '19 at 07:55
20

In unsigned arithmetic, you have added 0xFB to 0x84, i.e. 251 + 132, which indeed is larger than 8-bit, and so the carry flag is set.

In the second case, you are adding +127 to 1, which indeed exceeds a signed 8-bit range, and so the overflow flag is set.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • So the overflow is set only when I do 'add al, 1'? If I will delete this line, the overflow will not set? – Tom O Dec 13 '11 at 21:23
  • 1
    @Tom: The overflow will be set by both `add` instructions. – Oliver Charlesworth Dec 13 '11 at 21:24
  • So you can explain me please where the overflow set? because as I understood it, in the range of -128 to 127 is not affecting the overflow. – Tom O Dec 13 '11 at 21:31
  • 3
    @Tom O: Convert all your values to signed 8-bit. In the first `add`, you're doing -5 + -124, which exceeds -128. In the second `add`, you're doing +127 + +1, which exceeds +127. – Oliver Charlesworth Dec 13 '11 at 21:34