This article assumes that the reader has installed MASM32. If they have not, it is available from http://www.masm32.com/.
In this third and final part of this tutorial, I will cover the common arithmetic functions and some of the macros in MASM that considerably aid in the implementation of Assembler.
Increment and Decrement
The increment and decrement operations are inc and dec. For example:
TestProc proc mov eax, 5 dec eax dec eax mov dl, 10 inc dl inc dl ret TestProc endp
When using decrement dec, if the result is zero, the zero flag is set. This can be used to implement loops. For example:
TestProc proc mov ecx, 10 xor eax, eax ; efficient way of saying eax=0 LoopStart: inc eax dec ecx jnz LoopStart ; eax now equals 10 ret TestProc endp
Addition and Subtraction
The addition and subtraction instructions are add and sub. They take the general form of:
add/sub (destination), (source)
You can add registers to registers, registers to constants, and registers to the contents of memory. The size (in bits) of the source and destinations have to be the same. Both affect the flags of the system. For instance, if the result of a sub is zero, the zero flag is set. For example:
AddValues proc dwValue1:DWORD, dwValue2:DWORD mov eax, dwValue1 add eax, dwValue2 ret AddValues endp
This method adds the two values passed in and returns the result.
Multiplication and Division
The instructions for multiplication and division are mul and div. Both only operate on the accumulator register (eax) and use the data register (edx) as an overflow. The part of the registers affected are determined by the size of the operand.
The following diagram demonstrates how the accumulator and the data registers fit together when being used by the instructions.
Therefore, to get expected results, it is recommended that you set edx to zero before calling mul or div. For example:
TestProc proc mov eax, 10 xor edx, edx ; set edx to zero mul 10 div 10 ret TestProc endp
The usual logical operations are convered by or, and, and xor. They take the form as follows:
logical operation (destination), (source)
The size in bits of the source and and destination have to be the same. For instance:
LogicalFunction proc xor eax, eax ; the efficient way of saying eax=0 mov ax, 100 mov bx, 5 and ax, 1 or ax, bx ret LogicalFunction endp
The instructions shl and shr shift the given register bits left and right by the given bit count. These are highly efficient, and should be preferred over the mul and div instructions for parameters that are powers of two. For example:
ShiftFunction proc mov eax, 1 shl eax, 2 ; shift eax's bits left 2 times : i.e. eax *= 4 shr eax, 2 ; shift eax's bits right 2 times : i.e. eax /= 4 ret ShiftFunction endp