0
#include<stdio.h>
int myatoi(const char *string);
int main(int argc, char* argv[])
{ 
    printf("\n%d\n",
    myatoi("1998")); 
    getch(); 
    return(0);
}
int myatoi(const char* string)
{ 
    int value = 0;  
    if (string) 
    {    
        while (*string && (*string <= '9' && *string >= '0'))    
        {      
            value = (value * 10) + (*string - '0');  
            string++; 
        }
    }  
            return value; 
} 

What does *string - '0' mean?

2
Contributors
1
Reply
3
Views
4 Years
Discussion Span
Last Post by nullptr
0

(*string <= '9' && *string >= '0')
In hexadecimal this translates to *string <= 0x39 && *string >= 0x30

*string - '0'
Assume the number is 8, therefore *string would be in hex 0x38.
So 0x38 - 0x30 = 8

You could also use:
value = (value * 10) + (*string ^ 0x30);

BTW. The code posted won't work for a negative integer because it doesn't account for the - sign. It also should trim any leading whitespace and preferably check for overflow.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.