PROWAREtech

articles » current » c-plus-plus » procedures » atoi

C/C++: atoi Procedure (atol, atoul, atoll, atoull)

Convert ASCII c-string to a number.

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++;
	}

	return total;
}

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
		return total;
}

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++;
	}

	return total;
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE