Skip to content

Instantly share code, notes, and snippets.

@bynect
Created January 2, 2021 11:49
Show Gist options
  • Save bynect/f989a8c96dfe2ddb488b1ee1ee3c4702 to your computer and use it in GitHub Desktop.
Save bynect/f989a8c96dfe2ddb488b1ee1ee3c4702 to your computer and use it in GitHub Desktop.
A simple implementation of string (char *) to int conversion in ISO C.
/* 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