Date: 2008feb4
Language: C/C++
Q. Is there something faster than atoi() for converting ASCII to integers?
A. Yes, these functions do the trick.
// To convert a 1 digit ASCII number into an integer
inline int AsciiToInt(const char c)
{
return c - '0'; // Yes, its that easy
}
// To convert a 2 digit ASCII number into an integer
inline int AsciiToIntTwoDigits(const char s[2])
{
return AsciiToInt(*s) * 10 + AsciiToInt(s[1]);
}
// To convert any length ASCII number into an integer
inline int AsciiToInt(const char *p)
{
int result = 0;
int sign = 1;
// support negative
if (*p == '-')
{
sign = -1;
p++;
}
for (; *p; p++)
{
result = result * 10 + AsciiToInt(*p);
}
return sign * result;
}
Add a comment
Sign in to add a comment