4. Arithmetic Operations

You can perform addition, subtraction, multiplication, and division in assembly language. A addition and subtraction are performed using the add and sub instructions, respectively. These instructions take two operands: destination and source. The add instruction adds the source and destination and stores the result in the destination. The sub instruction subtracts the source from the destination operand, and the result is stored in the destination. These instructions set or clear flags in the eflags register, based on the operation. These flags can be used in the conditional statements. The sub instruction sets the zero flag, (zf), if the result is zero, and the carry flag, (cf), if the destination value is less than the source. The following outlines a few variations of these instructions:

add eax,42      ; same as eax = eax+42
add eax,ebx ; same as eax = eax+ebx
add [ebx],42 ; adds 42 to the value in address specified by ebx
sub eax, 64h ; subtracts hex value 0x64 from eax, same as eax = eax-0x64

There is a special increment (inc) and decrement (dec) instruction, which can be used to add 1 or subtract 1 from either a register or a memory location:

inc eax    ; same as eax = eax+1
dec ebx ; same as ebx = ebx-1

Multiplication is done using the mul instruction. The mul instruction takes only one operand; that operand is multiplied by the content of either the al, ax, or eax register. The result of the multiplication is stored in either the ax, dx and ax, or edx and eax register.

If the operand of the mul instruction is 8 bits (1 byte), then it is multiplied by the 8-bit al register, and the product is stored in the ax register. If the operand is 16 bits (2 bytes), then it is multiplied with the ax register, and the product is stored in the dx and ax register. If the operand is a 32-bit (4 bytes), then it is multiplied with the eax register, and the product is stored in the edx and eax register. The reason the product is stored in a register double the size is because when two values are multiplied, the output values can be much larger than the input values. The following outlines variations of mul instructions:

mul ebx  ;ebx is multiplied with eax and result is stored in EDX and EAX
mul bx ;bx is multiplied with ax and the result is stored in DX and AX

Division is performed using the div instruction. The div takes only one operand, which can be either a register or a memory reference. To perform division, you place the dividend (number to divide) in the edx and eax register, with edx holding the most significant dword. After the div instruction is executed, the quotient is stored in eax, and the remainder is stored in the edx register:

div ebx   ; divides the value in EDX:EAX by EBX
..................Content has been hidden....................

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