Solved

How do I implement atoi in C ?

Posted on 2003-12-09
13
1,044 Views
Last Modified: 2007-12-19
How do I implement atoi in C ?

Thanks.
0
Comment
Question by:paragm78
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +2
13 Comments
 
LVL 11

Expert Comment

by:KurtVon
ID: 9904263
The easiest way is to step theough the characters in the string and keep a running accumulation:

int atoi(char* p)
{
int num;

num = 0;
while (*p != 0)
{
    num = (10 * num) + *p - '0';
    p++;
}

That has no real error checking though.

Hope this helps.
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 9904272
Hi paragm78,

int i;
char * a = "123";
i = atoi(a);

just kidding ... but that is the way to go, unless you can assure us that this is not homework .. since I am suspicious, I'll post some important hints ...
1. you need to derive the numerical value of each char in the string ..eg. int 1 for first digit in 123, int 2 for second digit and so on
2. you need to determine the positional weight of that int ... e.g. 1 needs to multiplied by 100, 2 by 10 and 3 by1 ...
3. all that remains is the add the stuff together

only tricky part here is to determine the weights ... I can think of a few ways ... I'll post hints instead of directly listing them
1. determine the strlen before you start... getting weights then should be trivial
2. use a stack while getting digits .... pop will be in reverse order

Cheers!
Sunny:o)
0
 
LVL 11

Accepted Solution

by:
KurtVon earned 50 total points
ID: 9904337
Here's a slightly better version with error checking:

int atoi(char* p)
{
    int num;
    char bNeg;

    if (*p == '-')
    {
        bNeg = 1;
        p++;
    }
    else
        bNeg = 0;
    num = 0;
    while ((*p >= '0') && (*p <= '9'))
    {
        num = (10 * num) + *p - '0';
        p++;
    }
    if (bNeg)
        num *= -1;

    return num;
}

Hope this helps.

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 11

Expert Comment

by:KurtVon
ID: 9904364
Hi sunnycoder.

I looked at pragm78's question history and there didn't seem to be any serial homework-asking going on.  I've noticed that some version of embedded C leave out a number of "basic" ANSI functions, so I assume this is a legitimate question.  If it is homework, it's a pretty poor problem.

-Kurt
0
 
LVL 1

Expert Comment

by:travd
ID: 9906104
If this is for an embedded application where multiplication is an expensive operation you could replace the

(10*num)

by

num << 3 + num << 1

which might be considerably faster depending on the hardware.
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 9909848
Hi Kurt,

I appreciate that you took time to determine that the question was legitimate (which unfortunately, I did not) ... It indeed looks like I wrong.

Cheers
Sunny
0
 
LVL 11

Expert Comment

by:KurtVon
ID: 9912450
Don't worry about it Sunny, I only looked because I had the same suspicion.  Paragm78 should keep in mind that to avoid the danger of people thinking that, a little background as to what it is for helps.

Oh, and while num<<3+num<<1 is a neat fast way to do *10, a decent compiler should already do hardware optimizations like that itself.  Especially since on some embeded processors there are even more tricks for speeding up multiplication.  Unless the compiler is non-optimizing it is better to write stuff like that in the simplest way possible and count on the compiler to figure out the best way to do it.

We had a project where hand tuned assembly was transforming an image at 60 frames per second.  I re-wrote the routine in C with no hardware assumptions and used pragma to specify full speed optimization.  The routine ran at 80 frames per second.
0
 
LVL 1

Expert Comment

by:RajeshTN
ID: 9926545
Hi,
The code is as below:

int atoi(char *numStr)
{
 int integer=0;
 int i;
 if (numStr == NULL)
    return 0;
 for(i=strlen(numStr) -1;i>=0;i--)
 {
  if( numStr[i] >='0' && numStr[i] <='9' )  /*For Digits*/
  {
    integer=integer*10+ (numStr[i]-'0');
  }
  else if(numStr[i] == '-'  && i==0)    /*For sign*/
  {
   integer=0-integer;
  }
  else
   return 0;
 }
 return integer;
}

Regards
-Rajesh
0
 
LVL 1

Expert Comment

by:RajeshTN
ID: 9926780
Sorry paragm78 the above code given by me is wrong!!!,
The correct code is as below:

int atoi(char *numStr)
{
 int integer=0;
 int signflag=0;
 int i;
 if (numStr == NULL)
    return 0;
 for(i=0;i<strlen(numStr) ;i++)
 {
  if( numStr[i] >='0' && numStr[i] <='9' )  /*For Digits*/
  {
    integer=integer*10 + (numStr[i]-'0');
  }
  else if(numStr[i] == '-'  && i==0)    /*For sign*/
  {
   signFlag=1;  
  }
  else
   return 0;
 }
 return signflag?(0-integer):integer;
}

Regards
-Rajesh
0
 
LVL 1

Expert Comment

by:RajeshTN
ID: 9926819
Hi para,
You can replace "signflag" with "signFlag" everywhere in the code to remove errors
0
 

Expert Comment

by:indian_dingo
ID: 9941476
/* Here is another example */

/* function to convert char to int */
int local_atoi(char s[])
{
    long int i, n, sign;

    for (i = 0; isspace(s[i]); i++);
         sign = (s[i] == '-') ? -1 : 1;

    if (s[i] == '+' || s[i] == '-')
        i++;

    for (n = 0; isdigit(s[i]); i++)
        n = 10 * n + (s[i] - '0');

    return sign * n;
}
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
memory leak detection 9 111
libcurl - taking long time on curl_easy_perform 11 503
keep track of class structure 1 53
Excel formula to calculate ID # 4 42
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question