## C/C++ Example Procedure: ASCII c-string to number (atoi, atol, atoul, atoll, atoull)

See related: C/C++ Examples

See itoa to convert integers to ASCII c-strings. Convert ASCII decimal numbers to unsigned long long (64-bit) values.

``````// ASCII TO UNSIGNED LONG LONG
unsigned long long ATOULL(const char* sz)
{
int c;
unsigned long long total = 0;

// skip whitespace
while (*sz == ' ' || (*sz == '\n') | (*sz == '\r') | (*sz == '\t'))
++sz;

c = (int)(unsigned char)*sz++;

while ((c >= '0') & (c <= '9'))
{
total = 10 * total + (c - (int)'0'); // radix == 10
c = (int)(unsigned char)*sz++;
}

}
``````

Convert ASCII decimal numbers to long long values.

``````// ASCII TO LONG LONG
long long ATOLL(const char* sz)
{
int c; // ascii char
long long total = 0;
int sign;

// skip whitespace
while (*sz == ' ' || (*sz == '\n') | (*sz == '\r') | (*sz == '\t'))
++sz;

c = (int)(unsigned char)*sz++;
sign = c; // save sign
if (c == '-' || c == '+')
c = (int)(unsigned char)*sz++;

while ((c >= '0') & (c <= '9'))
{
total = 10 * total + (c - (int)'0'); // radix == 10
c = (int)(unsigned char)*sz++;
}

if (sign == '-')
return -total;
else
}
``````

Convert alpha-numeric numbers (specify a radix greater than 10) to unsigned long long values. 36 is a useful radix to specify in the itoa procedure.

``````// ALPHA-NUMERIC TO UNSIGNED LONG LONG (SPECIFY THE RADIX)
unsigned long long ANTOULL(const char* sz, unsigned radix)
{
int c;
unsigned long long total = 0;

// skip whitespace
while (*sz == ' ' || (*sz == '\n') | (*sz == '\r') | (*sz == '\t'))
++sz;

c = (int)(unsigned char)*sz++;

while (c)
{
total = radix * total + (c > '9' ? c - 'a' + 10 : c - '0');
c = (int)(unsigned char)*sz++;
}