Assembly Language for Beginners

(nextflipdebug2) #1

3.10. STRING TO NUMBER CONVERSION (ATOI())


; variable to be returned (rt) is in W0, ready to be used in caller function
ret
.L4:
mov w0, w1
ret


3.10.2 A slightly advanced example


My new code snippet is more advanced, now it checks for the “minus” sign at the first character and
reports an error if a non-digit has been found in the input string:


#include <stdio.h>


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


if (*s=='-')
{
negative=1;
s++;
};

while (*s)
{
if (*s<'0' || *s>'9')
{
printf ("Error! Unexpected char: '%c'\n", *s);
exit(0);
};
rt=rt*10 + (*s-'0');
s++;
};

if (negative)
return -rt;
return rt;
};


int main()
{
printf ("%d\n", my_atoi ("1234"));
printf ("%d\n", my_atoi ("1234567890"));
printf ("%d\n", my_atoi ("-1234"));
printf ("%d\n", my_atoi ("-1234567890"));
printf ("%d\n", my_atoi ("-a1234567890")); // error
};


Optimizing GCC 4.9.1 x64


Listing 3.27: Optimizing GCC 4.9.1 x64

.LC0:
.string "Error! Unexpected char: '%c'\n"


my_atoi:
sub rsp, 8
movsx edx, BYTE PTR [rdi]
; check for minus sign
cmp dl, 45 ; '-'
je .L22
xor esi, esi
test dl, dl
je .L20
.L10:

Free download pdf