25.12.2012 Views

MIPS Assembly Language Programming

MIPS Assembly Language Programming

MIPS Assembly Language Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2.8. LOADS: THE PALINDROME.ASM PROGRAM 35<br />

## $a0 - syscall parameters.<br />

## $a1 - syscall parameters.<br />

The first step of the algorithm is to read in the string from the user. This can be<br />

done with the read_string syscall (syscall number 8), which is similar in function<br />

to the fgets function in the C standard I/O library. To use this syscall, we need to<br />

load into register $a0 the pointer to the start of the memory that we have set aside<br />

to hold the string. We also need to load into register $a1 the maximum number of<br />

bytes to read.<br />

To set aside the space that we’ll need to need to store the string, the .space<br />

directive can be used. This gives the following code:<br />

.text<br />

main: # SPIM starts by jumping to main.<br />

## read the string S:<br />

la $a0, string_space<br />

li $a1, 1024<br />

li $v0, 8 # load "read_string" code into $v0.<br />

syscall<br />

.data<br />

string_space: .space 1024 # set aside 1024 bytes for the string.<br />

Once we’ve got the string, then we can use algorithm 2.2 (on page 34). The first<br />

step is simple enough; all we need to do is load the address of string_space into<br />

register $t1, the register that we’ve set aside to represent A:<br />

la $t1, string_space # A = S.<br />

The second step is more complicated. In order to compare the character pointed<br />

to by B with 0, we need to load this character into a register. This can be done with<br />

the lb (load byte) instruction:<br />

la $t2, string_space ## we need to move B to the end<br />

length_loop: # of the string:<br />

lb $t3, ($t2) # load the byte at B into $t3.<br />

beqz $t3, end_length_loop # if $t3 == 0, branch out of loop.<br />

addu $t2, $t2, 1 # otherwise, increment B,<br />

b length_loop # and repeat<br />

end_length_loop:<br />

subu $t2, $t2, 2 ## subtract 2 to move B back past<br />

# the ’\0’ and ’\n’.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!