Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly - Carry flag VS overflow flag

Tags:

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.

like image 775
Tom O Avatar asked Dec 13 '11 21:12

Tom O


People also ask

What is the overflow flag used for?

In computer processors, the overflow flag (sometimes called the V flag) is usually a single bit in a system status register used to indicate when an arithmetic overflow has occurred in an operation, indicating that the signed two's-complement result would not fit in the number of bits used for the result.

Is carry and overflow same?

Overflow and carry out are philosophically the same thing. Both indicate that the answer does not fit in the space available. The difference is that carry out applies when you have somewhere else to put it, while overflow is when you do not. As an example, imagine a four bit computer using unsigned binary for addition.

Is carry flag same as overflow flag?

Carry indicates the result isn't mathematically correct when interpreted as unsigned, overflow indicates the result isn't mathematically correct when interpreted as signed. So as examples for your 4-bit ALU: 1111 + 0001 = 0000 should set carry (15 + 1 = 0 is false) and clear overflow (-1 + 1 = 0 is true).

What is the carry flag in assembly?

Carry Flag is a flag set when: a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register.


2 Answers

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.

like image 146
Hassan Avatar answered Sep 18 '22 12:09

Hassan


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.

like image 42
Oliver Charlesworth Avatar answered Sep 20 '22 12:09

Oliver Charlesworth