Assembly Language for Beginners

(Jeff_L) #1

3.10 String to number conversion (atoi())


Non-optimizing Xcode 4.6.3 (LLVM) and Keil 6/2013


Non-optimizing LLVM does not generate the code we saw before in this section, but instead inserts a call
to the library function___divsi3.


What about Keil: it inserts a call to the library function__aeabi_idivmodin all cases.


3.9.4 MIPS.


For some reason, optimizing GCC 4.4.5 generate just a division instruction:


Listing 3.21: Optimizing GCC 4.4.5 (IDA)

f:
li $v0, 9
bnez $v0, loc_10
div $a0, $v0 ; branch delay slot
break 0x1C00 ; "break 7" in assembly output and objdump


loc_10:
mflo $v0
jr $ra
or $at, $zero ; branch delay slot, NOP


Here we see here a new instruction: BREAK. It just raises an exception.


In this case, an exception is raised if the divisor is zero (it’s not possible to divide by zero in conventional
math).


But GCC probably did not do very well the optimization job and did not see that $V0 is never zero.


So the check is left here. So if $V0 is zero somehow, BREAK is to be executed, signaling to theOSabout
the exception.


Otherwise, MFLO executes, which takes the result of the division from the LO register and copies it in $V0.


By the way, as we may know, the MUL instruction leaves the high 32 bits of the result in register HI and
the low 32 bits in register LO.


DIV leaves the result in the LO register, and remainder in the HI register.


If we alter the statement to “a % 9”, the MFHI instruction is to be used here instead of MFLO.


3.9.5 Exercise



3.10 String to number conversion (atoi())


Let’s try to reimplement the standard atoi() C function.


3.10.1 Simple example


Here is the simplest possible way to read a number represented inASCIIencoding.


It’s not error-prone: a character other than a digit leads to incorrect result.


#include <stdio.h>


int my_atoi (char *s)
{
int rt=0;


while (*s)
{
Free download pdf