如何使用输入的整数打印二进制数?

时间:2013-01-31 09:28:39

标签: assembly mips

我正在尝试将输入的整数转换为二进制,我似乎无法在程序中找到错误。我可以加载输入的数字以及打印出一个8位二进制数字,但是没有一个正在打印。我究竟做错了什么?

 enterNum: 
.asciiz "Enter your number (base 10):  "
 printBaseTwo: 
.asciiz "The number in base 2 is:  "
 #-----------------------------------------------------------------------

.text
#Print out string, collect intger input
main: li $v0, 4
      la $a0, enterNum
      syscall
  li $v0, 5
  syscall
  move $t0, $v0


#create mask/print out the second string and prepare to print out binary
mask: 
  andi $t1, $zero, 1
  sll $t1, $t1, 7
  addi $t2, $zero, 8
  li $v0, 4
  la $a0, printBaseTwo
  syscall


 # compares mask to integer, starting at the most sig place
 # if the mask is zero, print out zero
 loop: 
  and $t3,$t0, $t1
  beq $t3, $zero, print
  add $t3, $zero, $zero
  addi $t3, $zero, 1
  j print


 print: 
      #prepares to print integer in $a0
  li $v0, 1

      # moves either 1 or 0 into $a0 to be printed
  move $a0, $t3
  syscall

      # shifts over right 1, getting closer to 0
  srl $t1, $t1, 1

      #lowers count
  addi $t2, $t2, -1

      #loop back to beginning if not finished printing binary Num
  bne $t2, $zero, loop
  beq $t2, $zero, exit
 exit: 
  li $v0, 10
  syscall

1 个答案:

答案 0 :(得分:1)

我从32位MIPS版本开始回答这个问题。

首先,当要求十进制数时,MIPS将其保存为寄存器中的32位数字。因此,我做了以下调整:

andi $t1, $zero, 1
sll $t1, $t1, 7
addi $t2, $zero, 8

变为:

add $t1, $zero, 1
sll $t1, $t1, 31
addi $t2, $zero, 32

请注意我如何将andi更改为addi。如果您使用的是8位版本的MIPS,那么这将是唯一必要的调整。

我希望我解决了你的问题,它可以在MARS模拟器中工作!