assemblyx86binaryeflagssigned-overflow

what conditions set the overflow and carry flags?


I've been reading and watching tutorials but I only get more confused since my instructor did not go into much details with this, or her explanations are quite vague.

(The values in the flags were only dictated to us.)

Example 1:


  1010 1010 0100 0101
- 0100 0110 0111 1000
  ___________________
  0110 0011 1100 1101

SF = 0
ZF = 0
PF = 0
CF = 1
OF = 1
AF = 1

Why were CF and OF set to 1? And as I understand it, AF is set when there is a carry out of the b3 or a borrow into it, meaning it's the one who needs to borrow. Am I right?

Example 2:

  0110 0111 1011 0100
+ 1111 1010 1100 1110
_____________________
1 0110 0010 1000 0010

SF = 0
ZF = 0
PF = 0 
CF = 1 
OF = 1 
AF = 1

Here, AF was set because....? I thought AF is only set when there is a carry out of it (or when it needs to borrow)? Also, with CF, as I understand it, it cannot be set if there was a carry out of the MSB, and also a carry into it. It works like XOR, only one condition can be true.

This has been confusing me for days now. And yes, I'm still confused with the differences in how these flags work depending if the numbers are signed or unsigned, because my instructor never mentioned that to us.


Solution

  • example 1:

    mov     ax, 1010101001000101b
    mov     bx, 0100011001111000b
    sub     ax, bx
    

    example 2:

    mov     ax, 0110011110110100b   
    mov     bx, 1111101011001110b   
    add     ax, bx
    

    Here is the explanation from the intel manual:

    The status flags (bits 0, 2, 4, 6, 7, and 11) of the EFLAGS register indicate the results of arithmetic instructions, such as the ADD, SUB, MUL, and DIV instructions. The status flag functions are:
    CF (bit 0) Carry flag — Set if an arithmetic operation generates a carry or a borrow out of the mostsignificant bit of the result; cleared otherwise. This flag indicates an overflow condition for unsigned-integer arithmetic. It is also used in multiple-precision arithmetic.
    PF (bit 2) Parity flag — Set if the least-significant byte of the result contains an even number of 1 bits; cleared otherwise.
    AF (bit 4) Adjust flag — Set if an arithmetic operation generates a carry or a borrow out of bit 3 of the result; cleared otherwise. This flag is used in binary-coded decimal (BCD) arithmetic.
    ZF (bit 6) Zero flag — Set if the result is zero; cleared otherwise.
    SF (bit 7) Sign flag — Set equal to the most-significant bit of the result, which is the sign bit of a signed integer. (0 indicates a positive value and 1 indicates a negative value.)
    OF (bit 11) Overflow flag — Set if the integer result is too large a positive number or too small a negative number (excluding the sign-bit) to fit in the destination operand; cleared otherwise. This flag indicates an overflow condition for signed-integer (two’s complement) arithmetic.