Addition and subtraction

In addition (ADD) and subtraction (SUB), the OF, SF, and CF flags are affected. Let's see some examples of usage as instruction.

add eax, ecx adds whatever value is in the ecx register to the value in eax. The results of adding eax and ecx goes into eax.

Let's take the following example to see how it sets the OF, SF and CF flags:

mov ecx, 0x0fffffff
mov ebx, 0x0fffffff
add ecx, ebx

The registers are DWORDs. The ecx and ebx registers were set with 0x0fffffff (‭268,435,455‬), adding these results to 0x1ffffffe (‭536,870,910‬). SF was not set, since the result did not touch the most significant bit (MSB). CF was not set because the result is still within the capacity of a DWORD. Assuming that both were signed numbers, the result is still within the capacity of a signed DWORD number:

mov ecx, 0x7fffffff
mov ebx, 0x7fffffff
add ecx, ebx

The result in ecx becomes 0xfffffffe (-2). CF = 0; SF = 1; OF = 1. Assuming that both ecx and ebx were unsigned, the CF flag will not be set. Assuming that both ecx and ebx were signed numbers and both are positive numbers, the OF flag will be set. And since the most significant bit becomes 1, the SF flag is also set.

Now, how about adding two negative numbers? Let's consider the following example:

mov ecx, 0x80000000
mov ebx, 0x80000000
add ecx, ebx

Basically, we're adding both ecx and ebx, containing 0x80000000 (-2,147,483,648), the result of which becomes zero (0). CF = 1; SF = 0; OF = 1. The SF flag was not set since the MSB of the result is 0. Adding both MSB of ecx and ebx will definitely exceed the capacity of a DWORD value. At the signed number perspective, the OF flag is also set, since adding both negative values exceeds the signed DWORD capacity.

Let's try the borrow concept in this next example:

mov ecx, 0x7fffffff
mov edx, 0x80000000
sub ecx, edx

What happens here is that we are subtracting 0x80000000 (-2,147,483,648) from 0x7fffffff (‭2,147,483,647‬). In fact, what we are expecting is the sum of 2,147,483,648 and 2,147,483,647. The result in ecx becomes 0xffffffff (-1). CF = 1; SF = 1; OF = 1. Remember that we are doing a subtraction operation, thereby causing CF to be set, due to borrowing. The same goes for the OF flag.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.140.5