Reverse Engineering for Beginners

(avery) #1

CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI()) CHAPTER 42. STRING TO NUMBER CONVERSION (ATOI())


mov x2, x0
; X2=address of input string
; is loaded character zero?
; jump to exit if its so'
; W1 will contain 0 in this case.
; it will be reloaded into W0 at L4.
cbz w1, .L4
; W0 will contain "rt" variable
; initialize it at zero:
mov w0, 0
.L3:
; subtract 48 or '0' from input variable and put result into W3:
sub w3, w1, #48
; load next character at address X2+1 into W1 with pre-increment:
ldrb w1, [x2,1]!
add w0, w0, w0, lsl 2
; W0=W0+W0<<2=W0+W04=rt5
add w0, w3, w0, lsl 1
; W0=input digit + W0<<1 = input digit + rt52 = input digit + rt*10
; if the character we just loaded is not null byte, jump to the loop begin
cbnz w1, .L3
; variable to be returned (rt) is in W0, ready to be used in caller function
ret
.L4:
mov w0, w1
ret


42.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 was 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"));

Free download pdf