diff --git a/core/klibc.c b/core/klibc.c index e5c9537..512ef30 100644 --- a/core/klibc.c +++ b/core/klibc.c @@ -121,6 +121,34 @@ char *itoa(long long int value, char *str, int base) return rc; } +int atoi(const char *str) +{ + int sign = 1, base = 0, i = 0; + + // if whitespaces then ignore. + while (str[i] == ' ') { + i++; + } + + // sign of number + if (str[i] == '-' || str[i] == '+') { + sign = 1 - 2 * (str[i++] == '-'); + } + + // checking for valid input + while (str[i] >= '0' && str[i] <= '9') { + // handling overflow test case + if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) { + if (sign == 1) + return INT_MAX; + else + return INT_MIN; + } + base = 10 * base + (str[i++] - '0'); + } + return base * sign; +} + /* K&R */ void reverse(char s[]) { diff --git a/core/klibc.h b/core/klibc.h index 9d5e41b..d29103a 100644 --- a/core/klibc.h +++ b/core/klibc.h @@ -15,6 +15,7 @@ int memcmp(const void *s1, const void *s2, size_t n); void *memcpy(void *dest, const void *src, size_t n); void *memset(void *s, int c, size_t n); char *itoa(long long int value, char *str, int base); +int atoi(const char *str); void reverse(char s[]); int strlen(const char s[]); unsigned int strnlen(const char *s, size_t count);