Convert string to integer

From GbdevWiki
Revision as of 09:31, 13 August 2014 by A cat (Talk | contribs) (Created page with '<pre> unsigned int atoi(char* s, unsigned char len); unsigned int atoi(char* s, unsigned char len){ unsigned int val=0; unsigned int flag=0; unsigned char i; for(i=0;i<len;i++) …')

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
unsigned int atoi(char* s, unsigned char len);

unsigned int atoi(char* s, unsigned char len){
unsigned int val=0;
unsigned int flag=0;
unsigned char i;
for(i=0;i<len;i++)
{
    if(s[i] >= '0' && s[i] <= '9'){val = val * 10 + s[i] -'0';}
    else if(s[0] == '-' && i==0){flag = 1;}
    else{break;}
}
if(flag == 1)
val = val * -1;
return val;
}

example of the function being used:

char c[10] = "123";
int i = atoi(c, 3);
printf("%d", i);