Implementation of c functions itoa and atoi

Source: Internet
Author: User

1. itoa function implementation

#include 
 
  void itoa(int i, char *string){        int power=0,j=0;        j=i;        for( power=1;j>10;j/=10)                power*=10;        for(;power>0;power/=10)        {                *string++='0'+i/power;                i%=power;        }        *string='\0';        printf("%s\n",string);}void main(){        char string[20];        itoa(12345, string);        printf("%s\n",string);}
 

Among them, power is equivalent to 1234, and its power is 1000; 134, and its power is 100.

* String ++ = '0' + I/power; // obtain the asicii code of the obtained character.

I/power get characters, such as 1234/1000 = 1; 234/100 = 2


2. atoi implementation

int atoi(char *str){        if(!str)                return -1;        bool bMinus=false;        int result=0;        if(('0'>*str || *str>'9')&&(*str=='+'||*str=='-'))        {               if(*str=='-')                bMinus=true;               *str++;        }        while( *str != '\0')        {                if('0'> *str || *str>'9')                        break;                else                        result = result*10+(*str++ - '0');        }        if (*str != '\0')//no-normal end                return -2;        return bMinus?-result:result;}

The overwritten atoi function does not consider overflow.

If ('0'> * str | * str> '9') & (* str = '+' | * str = '-')) // determine whether the first character is the plus or minus sign of a number

If (* str! = '\ 0') // no-normal end. When the preceding while LOOP does not exit normally, the string is deemed invalid, for example, "+ 1234abc"

Test:

char *c1 = "12345";        char *c2 = "-12345";        char *c3 = "bat-123";        char *c4 = "+123abc";        printf("c1=%d\n",atoi(c1));        printf("c2=%d\n",atoi(c2));        printf("c3=%d\n",atoi(c3));        printf("c4=%d\n",atoi(c4));

Output result:

C1 = 12345
C2 =-12345
C3 =-2
C4 =-2


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.