Integer to String: itoa()

From Software Engineers Wiki
Jump to: navigation, search

Convert an integer to a string.

Answer #1

One way to convert an integer to a string is, writing each least significant digit first, then reverse the string. One thing to be careful is handling the negative number. Due to the computer design, negating INT_MIN results in an overflow if the storing variable is a signed integer. To avoid the overflow, it should be stored in an unsigned integer.

char *itoa(int value, char *str)
{
        unsigned int pos_value;
        char *cp = str;
        char *head, tmp;

        if (value < 0) {
                pos_value = -value;
                *cp++ = '-';
        } else
                pos_value = value;

        head = cp;

        do {
                *cp++ = '0' + (pos_value % 10);
                pos_value /= 10;
        } while (pos_value > 0);

        *cp-- = '\0';

        while (cp > head) {
                tmp = *head;
                *head++ = *cp;
                *cp-- = tmp;
        }

        return str;
}

Answer #2

Following code does not reverse string. It prints from the most significant digit first.

char *itoa(int value, char *str)
{
        unsigned int pos_value, tmp;
        char *cp = str;
        unsigned int order10;

        if (value < 0) {
                pos_value = -value;
                *cp++ = '-';
        } else
                pos_value = value;

        for (order10 = 1, tmp = pos_value; tmp >= 10; order10 *= 10, tmp /= 10)
                ;

        do {
                *cp++ = '0' + (pos_value / order10);
                pos_value %= order10;
                order10 /= 10;
        } while (pos_value > 0);

        *cp = '\0';

        return str;
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox