Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pop from the stack in MIPS assembly?

Tags:

stack

mips

I'm trying to learn MIPS assembly, since I've got some free time, and I'm trying to write a program that pushes numbers on to a stack, then pops them off. I want it to count the number of numbers popped before reaching a negative number and then each time it gets a negative one keep count of how many negative and positive numbers were popped.

so far I got this:

 #count the number of negative words on the stock by poping the stack until a non-    negative word is found 
#and print out the number of words found

.text
.globl main
#this code reads the numbers from the data area and stores in them in a stack
#the numbers are located in the test area and the number of numbers in the num area

main:   la $t0, test
lw $t1, num
loop:   lw $t2,($t0)
sub $sp, $sp, 4
sw $t2($sp)
add $t0, $t0, 4
add $t1, $t1, -1
bnez $t1, loop


#pop from the stack and print the number of numbers in the stack before a nonnegative number is reached 
#then keep count of how many negative and positive ones there are total

#code I cannot come up with would go here

.data
test:   .word
2, 0xfffabfff,2,-4,-9,0x99999999,0x90000000,-2147479536,0x80000000
num:    .word 10
ans:    .asciiz "Number is = "
endl:   .asciiz "\n"

I got it to push right, far as I can tell, but I cannot figure out the pushing and counting right. what do I have to do from here?

like image 725
user2060164 Avatar asked Apr 11 '13 19:04

user2060164


People also ask

How do I check if a stack is empty MIPS?

Capture the value of stack pointer before any of the dynamic pushing, and then as part of dynamic popping compare the current stack pointer with that previously captured stack pointer — when they are equal, there's nothing to pop.

What is $RA in MIPS?

On function entry, ra holds the return address where our caller wants us to jump when we're done. The function preamble saves it to the stack because the function body uses jal to make function calls.


1 Answers

A pop would be the opposite of a push. So if you use this to push $t2:

sub $sp,$sp,4
sw $t2,($sp)

You would pop it with:

lw $t2,($sp)
addiu $sp,$sp,4

Counting the number of negative words on the stack would be a matter of having a loop which pops a word off the stack, uses BGEZ to exit the loop if the popped value is >=0 or otherwise increases a counter and repeats.

like image 71
Michael Avatar answered Sep 18 '22 06:09

Michael