Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. #
  2. # reverse.asm
  3. # I'll probably improve on this over the semester,
  4. # as it was hacked up in about an hour.
  5. #
  6. # **** user input : The quick brown fox jumped over the lazy cat.
  7. # The quick brown fox jumped over the lazy cat.
  8. # 45
  9. # .tac yzal eht revo depmuj xof nworb kciuq ehT
  10. # -- program is finished running --
  11. #
  12. .data
  13. input: .space 256
  14. output: .space 256
  15.  
  16. .text
  17. .globl main
  18. main:
  19. li $v0, 8 # Ask the user for the string they want to reverse
  20. la $a0, input # We'll store it in 'input'
  21. li $a1, 256 # Only 256 chars/bytes allowed
  22. syscall
  23.  
  24. li $v0, 4 # We output the string to verify
  25. la $a0, input
  26. syscall
  27.  
  28. jal strlen # JAL to strlen function, saves return address to $ra
  29.  
  30. add $t1, $zero, $v0 # Copy some of our parameters for our reverse function
  31. add $t2, $zero, $a0 # We need to save our input string to $t2, it gets
  32. add $a0, $zero, $v0 # butchered by the syscall.
  33. li $v0, 1 # This prints the length that we found in 'strlen'
  34. syscall
  35.  
  36. reverse:
  37. li $t0, 0 # Set t0 to zero to be sure
  38. li $t3, 0 # and the same for t3
  39.  
  40. reverse_loop:
  41. add $t3, $t2, $t0 # $t2 is the base address for our 'input' array, add loop index
  42. lb $t4, 0($t3) # load a byte at a time according to counter
  43. beqz $t4, exit # We found the null-byte
  44. sb $t4, output($t1) # Overwrite this byte address in memory
  45. subi $t1, $t1, 1 # Subtract our overall string length by 1 (j--)
  46. addi $t0, $t0, 1 # Advance our counter (i++)
  47. j reverse_loop # Loop until we reach our condition
  48.  
  49. exit:
  50. li $v0, 4 # Print
  51. la $a0, output # the string!
  52. syscall
  53.  
  54. li $v0, 10 # exit()
  55. syscall
  56.  
  57.  
  58. # strlen:
  59. # a0 is our input string
  60. # v0 returns the length
  61. # -- This function loops over the character array until it encounters
  62. # the null byte, interestingly, the 0x0a character is stored by default
  63. # for input strings requested through the syscall. So we just subtract one
  64. # from the end result.
  65.  
  66. strlen:
  67. li $t0, 0
  68. li $t2, 0
  69.  
  70. strlen_loop:
  71. add $t2, $a0, $t0
  72. lb $t1, 0($t2)
  73. beqz $t1, strlen_exit
  74. addiu $t0, $t0, 1
  75. j strlen_loop
  76.  
  77. strlen_exit:
  78. subi $t0, $t0, 1
  79. add $v0, $zero, $t0
  80. add $t0, $zero, $zero
  81. jr $ra
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement