我目前正在构建一个程序,将十进制数转换为二进制数(32位,用左填充零和每4个数字一个空格),因为我没有立即实现它的级别。只是用伪代码计划整个过程。
这是我到目前为止(两种方式):
第一个:
list. space 128 #create an array for 32 integers
beq i=32-1, -1 #if the last index of array is <0
div n, 2 #n is the input number
list[i]= mfHi #store remainder in the last index
n = mfhi #quotient would be the new n
i--
对于这种情况,在此循环之后,除了转换后的二进制部分以外,数组中的其他索引将用零填充,因为该数字总共被除以32次。
第二种方法是将其存储在字符串中,进行循环直到n变为0,然后将n除以2。然后,我们将字符串反转并填充零。
这两个解决方案是否可以实施?还是我应该改变方式。欢迎发表任何评论,谢谢。
您必须在除法之前存储余数,否则输入的余数将不被存储。请看一下这段代码并尝试理解它。
.data
list: .space 128 #create an array for 32 integers
string: .asciiz "Enter a number : "
.text
.globl main
main:
jal converter_dec_bin
# End Program
li $v0, 10
syscall
converter_dec_bin:
addiu $sp,$sp,-8
sw $ra,0($sp)
xor $t1,$t1,$t1
xor $t2,$t2,$t2
addiu $t2,$t2,504 # 126*4
addiu $t1,$t1,1522 # input number
loop:
rem $t3,$t1,2
sw $t3,list($t2)
subiu $t2,$t2,4
divu $t1,$t1,2
bne $t1,0,loop
xor $t4,$t4,$t4
fill_list:
sw $t4,list($t2)
subiu $t2,$t2,4
bne $t2,0,fill_list
xor $t2,$t2,$t2
print_out:
li $v0, 1
lw $t0,list($t2)
move $a0, $t0
syscall
addiu $t2,$t2,4
bne $t2,508,print_out
lw $ra,0($sp)
addiu $sp,$sp,8
jr $ra
感谢您的回答,似乎您已使用堆栈来实现此目的。但是,自从我今天才开始学习MIPS以来,我一直很难理解代码。这就是我尝试使用数组实现的内容。错误太多...。数据输入:.asciiz“输入整数:”ipnum:.asciiz“输入数字为”Bin:.asciiz“二进制:”Qtr:.asciiz“第四纪:”十月:.asciiz“八进制:”新增:.asciiz“ \ n”列表:.space 128
.text
.globl main
main:
la $a0, enter #load address into $a0
li $v0, 4 #call to print string
syscall
li $v0, 5 #read integer
syscall
move $t0, $v0 #inter stored in $t0
la $a0, new #print two new lines
li $v0, 4
syscall
la $a0, new
li $v0, 4
syscall
la $a0, ipnum #print the string
li $v0, 4
syscall
li $v0, 1 #print the input number
move $a0, $t0
syscall
la $a0, new #print two new lines
li $v0, 4
syscall
la $a0, new
li $v0, 4
syscall
la $a0, Bin #print "Binary:"
li $v0, 4
syscall
binary:
li $s0, 0 #index i
li $t1, 2 #assign 2 into t1
div $t0, $t1 #
mfhi $t2 #set remainder as t2
sw $t2, 0($s0) #save remiander to the ith index of array
mflo $t0 #input number now become quotient
addi $s0, $s0, 4 #i = i+4, since dealing with integer
beq $t0, $zero, print
j binary
#print backwards from the last indext of the array
print:
beq $a1, -4, exit #if finished printing until list[0]
li $a1, 128 #set $a1 as 128 to print last index of myArray
lw $t3, list($a1)
li $v0 1 #print out the number
move $a0, $t3
syscall
addi $a1, $a1, -4 #i = i-4
j print
exit:
li $v0, 10
syscall