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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With