Sign, Carry, and Overflow Flag (Assembly)

6.3k views Asked by At
.data
val1 BYTE 10h
val2 WORD 8000h
val3 DWORD 0FFFFh
val4 WORD 7FFFh

If val2 is incremented by 1 using the ADD instruction, what will be the values of the Carry and Sign flags?

If val4 is incremented by 1 using the ADD instruction, what will be the values of the Over- flow and Sign flags?

I answered both and got them both wrong. Why is the answer what it is?

3

There are 3 answers

0
rkhb On

Imagine it as a kind of analog clock. In a real clock the times "six fifty-five" (55) and "five to seven" (-5) are identical. It's just an issue of your definition, the clock itself doesn't know your definition and runs round and round and round... The same with the CPU. Look at the following "CPU-clock":

CPU-clock (Addition)

I've chosen a 4-bit-clock, but the principle is the same for every other group of bits (BYTE, WORD, DWORD etc.).

The carry flag will be set after the clock has jumped from 15 to 0. It is in this case a flag for unsigned overflow.

The overflow flag will be set after the clock has jumped from 7 to -8. It flags a signed overflow.

The sign flag flags a value which can be interpreted as a negative number.

The behavior of the flags is a little bit different, if you count downwards:

CPU-clock (Subtraction)

14
Spektre On

1.specify platform flags can be set differently on different platform

2.also what bit wide the used instructions are?

 8000h
+0001h
------
 8001h -> Carry=0,Sign16=1

 7FFFh
+0001h
------
 8000h -> Carry=0,Sign16=1
  • most CPU's does not handle numbers as signed instead use 2'os complement binary representation
0
Ruud Helderman On

Trying to summarize what was already discussed in most of the comments...

x86, as well as all other processor architectures I've seen so far, have no real notion of signed and unsigned numbers. It is your interpretation that determines whether the 16-bit value 8000h is +32768 (unsigned) or -32768 (signed).

There are no separate signed and unsigned instructions to add and subtract; again, you decide whether 7FFFh + 0001h is a valid (unsigned) addition, or an overflow (since 7FFFh is the maximum signed integer in 16-bit twos' complement).

To help you as a programmer, the arithmetic operations set flags for both interpretations. After the operation has completed, you test the appropriate flags. Rule of thumb:

  • for signed numbers, test the overflow and sign flag
  • for unsigned numbers, test the carry flag; it acts more or less as an 'unsigned overflow'

Examples:

  • 7FFFh + 1 overflows when signed (OF is set), not when unsigned (CF = 0); the result 8000h is negative when signed (SF = 1)
  • FFFFh + 1 overflows when unsigned (CF is set), not when signed (OF = 0); the result 0000h is not negative (SF = 0)