90 likes | 280 Views
ICS 51 – Discussion 3. Multiplication , Division, and Stack. Multiplication Operation. Unsigned multiplication: MUL Code: MUL Operand If Operand is a byte , e.g. MUL BL , then AX = AL*Operand If Operand is a word , e.g., MUL BX , then DX:AX = AX*Operand
E N D
ICS 51 – Discussion 3 Multiplication, Division, and Stack
Multiplication Operation • Unsigned multiplication: MUL • Code: MUL Operand • If Operand is a byte, e.g. MUL BL, thenAX = AL*Operand • If Operand is a word, e.g., MUL BX, thenDX:AX = AX*Operand • If Operand is a dword, e.g., MUL EBX, thenEDX:EAX = EAX*Operand • Signed multiplication: IMUL • (look up the code table)
MUL Examples • Mov EAX, 0 // Clear EAX • Mov AL, 5 //First number • Mov BL, 10 //Second number • Mul BL //Multiply 2 numbers • Where and what is the result? • AX = AL*BL = 50
MUL Examples (cont.) • Mov EDX, 0 //clear EDX • Mov EAX, 0 //clear EAX • MovAX, 4460 //first number • Mov BX, 1000 //second number • MulBX //multiply 2 numbers • Where and what is the result? • DX:AX = AX*BX = 4,460,000 • 4,460,000 = 440DE0 in Hex: • DX has 0x0044, AX has 0x0DE0
Division Operation • Unsigned division: DIV • Code: DIV Operand • If Operand is a byte, e.g. DIV BL, thenAL = AX/Operand AH = Rest • If Operand is a word, e.g., DIV BX, thenAX = DX:AX/Operand DX = Rest • If Operand is a dword, e.g., DIV EBX, thenEAX = EDX:EAX/Operand EDX = Rest • Signed division: IDIV • (look up the code table)
DIV Example • Mov EDX, 70001 //dividend • Mov AX, DX //move lower 2 bytes to AX • Shr EDX, 16 //DX has the higher 2 bytes • Mov CX, 2 //divisor • Div CX //divide 70001 by 2 • Result: • Quotient = AX = DX:AX / CX = 35000 • Remainder = DX = 1
Why Using Stack • What if we run out of registers? • What if the registers you are going to use are currently used by other functions? • Answers = PUSH and POP
Stack Push/Pop Examples • … run out of registersPush EAX //save EAX on the stackPush EBX //save EBX on the stack … use EAX and EBX for some calculations …Pop EBX //move top of the stack to EBXPop EAX //move top of the stack to EAX to restore its original value • Note the orders of PUSH and POP are reversed
Stack Push/Pop Examples (cont.) • void functionXXX(){ __asm { Push EAX Push EBX … Pop EBX Pop EAX }}