Link to home
Start Free TrialLog in
Avatar of bfields
bfields

asked on

Coding an atoi( ) function

How do I code my own atoi() function?
Avatar of billyh
billyh

Why code your own function, it will take you valuable time and its more likely to have bugs. It's better to just use atoi as it has been tested and developed by good programmers.

Or may there is something more that you want that atoi does not offer you?
Avatar of bfields

ASKER

As a problem-solving exercise/brain teaser I would like to code my own.  For starters just taking an integer and getting it into a string without using atoi, etc...
ASKER CERTIFIED SOLUTION
Avatar of billyh
billyh

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ozo
pow?  to code an atoi function?  homework or not, I can't let that pass without comment

unsigned int my_own(char* str_var){
    unsigned int local_var = 0;
    while( *str_var ){
        local_var *= 10;
        local_var += (int)*str_var++ - '0';
    }
    return local_var;
}
You really don't need pow to code atoi(). I guess ozo's solution is more elegant. However, it should check whether the string represents a negative integer ("-1234"). Some more checks to make sure that the character represents a digit is required. Perhaps ozo's code with the following changes would be more meaningful.
     int my_own(char* str_var){
         int local_var = 0,sign;
         sign=(*str_var=='-')?-1:1;
         if(*str_var=='-' || *str_var=='+) str_var++;
         while( isdigit(*str_var) ){
             local_var *= 10;
             local_var += (int)*str_var++ - '0';
         }
         return sign * local_var;
     }

Thanks
pagladasu
Avatar of bfields

ASKER

This was a good solution.  Two things he should have checked for.  Negative # and non digit characters.
Guys I accept that when I wrote the program I was not thinking about efficiency, that's why I used pow. You will have to admit that when coding within a 30 minute time, one is bound to make such mistakes.

As for negatives, PLEASE look-up the meaning of unsigned integer. There are no negative numbers in unsigned integers, the first bit which is usually used for the negative numbers is considered as part of the number in unsigned numbers.

That is why 0xffffffff not -1, but 4294967295.

As for non-numberical, I believe bfields said he wanted a brain-teaser. I gave him an idea, now he should enjoy doing the rest.