Convert integer to string without access to libraries

The algorithm is easy to see in English.

Given an integer, e.g. 123

  1. divide by 10 => 123/10. Yielding, result = 12 and remainder = 3

  2. add 30h to 3 and push on stack (adding 30h will convert 3 to ASCII representation)

  3. repeat step 1 until result < 10

  4. add 30h to result and store on stack

  5. the stack contains the number in order of | 1 | 2 | 3 | ...


A look on the web for itoa implementation will give you good examples. Here is one, avoiding to reverse the string at the end. It relies on a static buffer, so take care if you reuse it for different values.

char* itoa(int val, int base){

    static char buf[32] = {0};

    int i = 30;

    for(; val && i ; --i, val /= base)

        buf[i] = "0123456789abcdef"[val % base];

    return &buf[i+1];

}

fast stab at it: (edited to handle negative numbers)

int n = INT_MIN;
char buffer[50];
int i = 0;

bool isNeg = n<0;

unsigned int n1 = isNeg ? -n : n;

while(n1!=0)
{
    buffer[i++] = n1%10+'0';
    n1=n1/10;
}

if(isNeg)
    buffer[i++] = '-';

buffer[i] = '\0';

for(int t = 0; t < i/2; t++)
{
    buffer[t] ^= buffer[i-t-1];
    buffer[i-t-1] ^= buffer[t];
    buffer[t] ^= buffer[i-t-1];
}

if(n == 0)
{
    buffer[0] = '0';
    buffer[1] = '\0';
}   

printf(buffer);