Created
January 2, 2021 11:49
-
-
Save bynect/f989a8c96dfe2ddb488b1ee1ee3c4702 to your computer and use it in GitHub Desktop.
A simple implementation of string (char *) to int conversion in ISO C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Naive implementation of string (char *) to int conversion in ISO C. */ | |
int | |
strtoi(const char *str, unsigned int len) | |
{ | |
int i, neg, num; | |
unsigned int val, pow; | |
if (str == 0 || len == 0) | |
return 0; | |
if (*str == '-') | |
{ | |
++str; | |
--len; | |
neg = 1; | |
} else | |
neg = 0; | |
for (i = len - 1, val = 0, pow = 1; i >= 0; --i) | |
{ | |
num = str[i] - '0'; | |
if (num < 0 || num > 9) | |
break; | |
val += num * pow; | |
pow *= 10; | |
} | |
return neg ? -val : val; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment