Reverse Engineering for Beginners

(avery) #1

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


Chapter 42


String to number conversion (atoi())


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


42.1 Simple example


Here is the simplest possible way to read a number represented inASCII^1 encoding. 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)
{
rt=rt*10 + (*s-'0');
s++;
};

return rt;
};


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


So what the algorithm does is just reading digits from left to right. The zeroASCIIcharacter is subtracted from each digit.
The digits from “0” to “9” are consecutive in theASCIItable, so we do not even need to know the exact value of the “0”
character. All we need to know is that “0” minus “0” is 0, “9” minus “0”’is 9 and so on. Subtracting “0” from each character
results in a number from 0 to 9 inclusive. Any other character leads to an incorrect result, of course! Each digit has to be
added to the final result (in variable “rt”), but the final result is also multiplied by 10 at each digit. In other words, the result
is shifted left by one position in decimal form on each iteration. The last digit is added, but there is no no shift.


42.1.1 Optimizing MSVC 2013 x64.


Listing 42.1: Optimizing MSVC 2013 x64

s$ = 8
my_atoi PROC
; load first character
movzx r8d, BYTE PTR [rcx]
; EAX is allocated for "rt" variable
; its 0 at start'
xor eax, eax
; first character is zero-byte, i.e., string terminator?


(^1) American Standard Code for Information Interchange

Free download pdf