25.12.2012 Views

MIPS Assembly Language Programming

MIPS Assembly Language Programming

MIPS Assembly Language Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

36 CHAPTER 2. <strong>MIPS</strong> TUTORIAL<br />

Note that the arithmetic done on the pointer B is done using unsigned arithmetic<br />

(using addu and subu). Since there is no way to know where in memory a pointer<br />

will point, the numerical value of the pointer may well be a “negative” number if it<br />

is treated as a signed binary number .<br />

When this step is finished, A points to the first character of the string and B points<br />

to the last. The next step determines whether or not the string is a palindrome:<br />

test_loop:<br />

bge $t1, $t2, is_palin # if A >= B, it’s a palindrome.<br />

lb $t3, ($t1) # load the byte at address A into $t3,<br />

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

bne $t3, $t4, not_palin # if $t3 != $t4, not a palindrome.<br />

# Otherwise,<br />

addu $t1, $t1, 1 # increment A,<br />

subu $t2, $t2, 1 # decrement B,<br />

b test_loop # and repeat the loop.<br />

The complete code for this program is listed in section 5.4 (on page 74).<br />

2.9 The atoi Program<br />

The next program that we’ll write will read a line of text from the terminal, interpret<br />

it as an integer, and then print it out. In effect, we’ll be reimplementing the read_int<br />

system call (which is similar to the GetInteger function in the Roberts libraries).<br />

2.9.1 atoi-1<br />

We already know how to read a string, and how to print out a number, so all we need<br />

is an algorithm to convert a string into a number. We’ll start with the algorithm<br />

given in 2.3 (on page 37).<br />

Let’s assume that we can use register $t0 as S, register $t2 as D, and register<br />

$t1 is available as scratch space. The code for this algorithm then is simply:<br />

li $t2, 0 # Initialize sum = 0.<br />

sum_loop:<br />

lb $t1, ($t0) # load the byte *S into $t1,<br />

addu $t0, $t0, 1 # and increment S.

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

Saved successfully!

Ooh no, something went wrong!