Advertisement
Davi0k

RPN calculator written in MIPS Assembly

Sep 10th, 2022 (edited)
3,161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
ARM 1.55 KB | Software | 0 0
  1.     .globl main
  2.  
  3.     .data
  4. input: .asciiz "15 5 * 7 8 + 5 * -" # The RPN (Reverse Polish Notation) expression to evaluate
  5.  
  6.     .text
  7. macros:
  8.     .macro print_int(%reg)
  9.         li $v0 1
  10.         move $a0 %reg
  11.         syscall
  12.     .end_macro
  13.    
  14.     .macro terminate()
  15.         li $v0 10
  16.         syscall
  17.     .end_macro
  18.    
  19.     .macro operation (%operator)
  20.         lw $a0 0($sp)
  21.         addi $sp $sp 4
  22.        
  23.         lw $a1 0($sp)
  24.         addi $sp $sp 4
  25.        
  26.         %operator $v0 $a0 $a1
  27.        
  28.         addi $sp $sp -4
  29.        
  30.         sw $v0 0($sp)
  31.        
  32.         addi $t1 $t1 1
  33.        
  34.         j loop
  35.     .end_macro
  36.    
  37. main:
  38.     la $s0 input
  39. loop:  
  40.     add $s2 $s0 $t1
  41.  
  42.     lb $t0 0($s2)
  43.    
  44.     beq $t0 0 end
  45.    
  46.     beq $t0 43 plus
  47.     beq $t0 45 minus
  48.     beq $t0 42 star
  49.    
  50.     beq $t0 32 space
  51.    
  52.     j number
  53.    
  54. plus:
  55.     operation(add)
  56. minus:
  57.     operation(sub)
  58. star:
  59.     operation(mul)
  60. space:
  61.     addi $t1 $t1 1
  62.    
  63.     j loop
  64. number:
  65.     move $a0 $s0
  66.     move $a1 $t1
  67.     jal str_to_int
  68.    
  69.     addi $sp $sp -4
  70.    
  71.     sw $v0 0($sp)
  72.    
  73.     add $t1 $t1 $v1
  74.    
  75.     j loop
  76. end:
  77.     lw $s5 0($sp)
  78.     addi $sp $sp 4
  79.    
  80.     print_int($s5)
  81.    
  82.     terminate()
  83.  
  84. # Function to convert a string into an integer
  85. # $a0 -> The ASCII string which contains the number to convert - $a1 -> The index of the first character of the number to convert
  86. # $v0 <- The converted number value expressed as a word - $v1 <- The number of digits which compose the converted number
  87. str_to_int:
  88.     li $v0 0
  89.    
  90.     li $v1 0
  91.    
  92.     add $t7 $a0 $a1
  93.    
  94. init:
  95.     add $t8 $t7 $v1
  96.    
  97.     lb $t9 0($t8)
  98.    
  99.     bgt $t9 57 not_a_number
  100.    
  101.     blt $t9 48 not_a_number
  102.    
  103.     mul $v0 $v0 10
  104.    
  105.     subi $t9 $t9 48
  106.    
  107.     add $v0 $v0 $t9
  108.    
  109.     addi $v1 $v1 1
  110.  
  111.     j init
  112. not_a_number:
  113.     jr $ra
Tags: Script
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement