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.

2.9. THE ATOI PROGRAM 39<br />

end_sum_loop:<br />

mul $t2, $t2, $t3 # set the sign properly.<br />

A complete program that incorporates these changes is in atoi-2.asm.<br />

2.9.3 atoi-3<br />

While the algorithm in atoi-2.asm is better than the one used by atoi-1.asm, it is<br />

by no means free of bugs. The next problem that we must consider is what happens<br />

when S does not point to a proper string of digits, but instead points to a string that<br />

contains erroneous characters.<br />

If we want to mimic the behavior of the UNIX atoi library function, then as<br />

soon as we encounter any character that isn’t a digit (after an optional ’-’) then we<br />

should stop the conversion immediately and return whatever is in D as the result. In<br />

order to implement this, all we need to do is add some extra conditions to test on<br />

every character that gets read in inside sum_loop:<br />

sum_loop:<br />

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

addu $t0, $t0, 1 # and increment S,<br />

## use 10 instead of ’\n’ due to SPIM bug!<br />

beq $t1, 10, end_sum_loop # if $t1 == \n, branch out of loop.<br />

blt $t1, ’0’, end_sum_loop # make sure 0 = t1<br />

mul $t2, $t2, 10 # t2 *= 10.<br />

sub $t1, $t1, ’0’ # t1 -= ’0’.<br />

add $t2, $t2, $t1 # t2 += t1.<br />

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

end_sum_loop:<br />

A complete program that incorporates these changes is in atoi-3.asm.<br />

2.9.4 atoi-4<br />

While the algorithm in atoi-3.asm is nearly correct (and is at least as correct as the<br />

one used by the standard atoi function), it still has an important bug. The problem

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

Saved successfully!

Ooh no, something went wrong!