Programming Tips - C/C++: Something faster than atoi() for converting ASCII to integers

Date: 2008feb4 Update: 2026sep26 Language: C/C++ Keywords: fast, speed, integer Q. C/C++: Something faster than atoi() for converting ASCII to integers A. 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. You can add some error checking if you want } // 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++) { if (!isdigit(*p)) break; result = result * 10 + AsciiToInt(*p); } return sign * result; }
Full Example Use:
#include <stdio.h> #include <ctype.h> // (Place the above functions here) int main() { { const char *number = "123456"; const int n = AsciiToInt(number); printf("%s is converted to %d\n", number, n); } { const char *number = "-888"; const int n = AsciiToInt(number); printf("%s is converted to %d\n", number, n); } { const char *number = "3.14"; const int n = AsciiToInt(number); printf("%s is converted to %d\n", number, n); } }
Output:
123456 is converted to 123456 // Works fine -888 is converted to -888 // Negative is OK 3.14 is converted to 3 // Stops at the first non-digit