PROWAREtech

articles » current » c-plus-plus » procedures » itoa

C/C++: itoa Procedure (ltoa, ultoa, lltoa, ulltoa)

Convert a number to an ASCII c-string.

See atoi to convert ASCII c-strings to integers. By specifying a radix of 26 or more, a c-string number can be shortened significantly. This increased the base of the number. Use a radix of 16 for hexadecimal output.

// 64-BIT NUMBER TO ASCII (USED BY LLTOA AND ULLTOA)
inline char* I64TOA(unsigned long long val, char* sz, unsigned radix, int neg)
{
	char* p = sz;
	char* first;
	unsigned long long dig;

	if (neg)
	{
		val = (unsigned long long)(-(long long)val);
		*p++ = '-';
	}

	first = p;

	do {
		dig = (unsigned)(val % radix);
		val /= radix;

		if (dig > 9)
			*p++ = (char)(dig - 10 + 'a');  // a letter
		else
			*p++ = (char)(dig + '0');       // a digit
	} while (val > 0);

	*p-- = '\0';

	char tmp;

	do {
		tmp = *p;
		*p = *first;
		*first = tmp;
		--p;
		++first;
	} while (first < p);
	return sz;
}

// CONVERT SIGNED LONG LONG TO ASCII
char* LLTOA(long long val, char* sz, unsigned radix)
{
	return I64TOA((unsigned long long)val, sz, radix, radix == 10 && val < 0);
}

// CONVERT UNSIGNED LONG LONG TO ASCII
char* ULLTOA(unsigned long long val, char* sz, unsigned radix) // specify the radix of 36 to make alpha-numeric c-string number
{
	return I64TOA(val, sz, radix, 0);
}

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