Division and Multiplication in Assembly Language (MIPS32 ISA)
Tanvir Ahmed Khan
2 min read
💡
You can use Cpulator (Online Simulator) to execute this code.
💡
Remember to set the stack pointer beforehand, otherwise, it might throw you an 'overflow' error. The stack pointer is typically initialized to the highest address in the data segment.
li $sp, 0x7ffffffc # Setting the stack to highest stack address
Multiplication:
First, we'll attempt to include this C logic in the MIPS assembly program for the Multiplication.
Multiply(a, b) {
int res = 0
for(int i=0;i<b;i++) res += a
}
This is a simple program that can be implemented in MIPS32.
💡
We are using procedures (Functions) for Division and Multiplication
Here is the code for Multiplication (MIPS32 ISA)
MULTIPLY:
# While (idx < b) result += A
add $sp, $sp, -16 # Allocating Stack Memory
sw $s3, 12($sp) # Storing register values
sw $s2, 8($sp)
sw $s1, 4($sp)
sw $s0, 0($sp)
add $s0, $zero, $zero # Result = 0
addi $s1, $zero, 0 # idx (t0) = 0
add $s2, $zero, $a0 # s2 = A
add $s3, $zero, $a1 # s3 = B
MULTIPLY_LOOP:
beq $s3, $s1, EXIT_MULTIPLY # if (idx == b) Break
add $s0, $s0, $s2 # result += A
addi $s1, $s1, 1 # idx++
j MULTIPLY_LOOP
EXIT_MULTIPLY:
add $v0, $zero, $s0 # v0 = Result
lw $s3, 12($sp) # restoring register values
lw $s2, 8($sp)
lw $s1, 4($sp)
lw $s0, 0($sp)
add $sp, $sp, 16 # restoring stack pointer
jr $ra
Division:
First, we'll attempt to include this C logic in the MIPS assembly program for the Division.
division(a, b) {
int res = 0;
while(a >= b){
a -= b;
res += 1;
}
return res;
}
Here is the code for Division (MIPS32 ISA)
DIVISION:
# While (A >= B) A -= B; result++
add $sp, $sp, -12 # Allocating Stack Memory
sw $s2, 8($sp) # Storing register values
sw $s1, 4($sp)
sw $s0, 0($sp)
addi $s0, $zero, 0 # result (s0) = 0
add $s1, $zero, $a0 # s1 = A
add $s2, $zero, $a1 # s2 = B
DIV_LOOP:
blt $s1, $s2, EXIT_DIV # If (A < B) break
sub $s1, $s1, $s2 # A -= B
addi $s0, $s0, 1 # result++
j DIV_LOOP
EXIT_DIV:
add $v0, $zero, $s0 # v0 = result
lw $s2, 8($sp) # restoring register values
lw $s1, 4($sp)
lw $s0, 0($sp)
addi $sp, $sp, 12 # restoring stack pointer
jr $ra
Conclusion:
In this article, you have learned to implement division and multiplication in Mips32 ISA
0
Subscribe to my newsletter
Read articles from Tanvir Ahmed Khan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Tanvir Ahmed Khan
Tanvir Ahmed Khan
Undergraduate Student from Bangladesh