如何在MIPS汇编中从堆栈中弹出元素?

5

我正在学习MIPS汇编语言,因为我有些空闲时间,我试图编写一个程序,将数字推到堆栈上,然后将其弹出。我希望它在遇到负数之前计算弹出的数字数量,并且每次得到一个负数时都计算弹出了多少个负数和正数。

目前为止,我已经写出了以下代码:

 #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"

我设法将其向右推,据我所知,但我无法弄清楚正确的推和计数。从这里开始我该怎么做?

1个回答

7

弹出(pop)是推送(push)的相反操作。因此,如果您使用它来推送$t2

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

你可以使用以下方法打开它:

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

统计堆栈中负数单词的数量将涉及到一个循环,该循环弹出堆栈中的一个单词,使用BGEZ指令退出循环,如果弹出的值 >=0,则增加计数器并重复执行。


3
我知道我要求非常苛刻,但“sub”指令不支持立即数操作数,应该使用“addi $sp, $sp, -4”。请注意,这只是微小的细节问题。 - Stefano Sanfilippo
它很可能被汇编器识别为伪指令,并被翻译成addiu - Michael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接