Convert a long string to a string using guarentee.

I am trying to convert long to a string in a memory allocator, so I need to avoid using heap memory.

I was thinking about using sprintf, but somewhere in the line it uses heap memory, like in the call stack that I receive. those. LocaleUpdate. Is there an easy way to do this?

+4
source share
1 answer
/**
 * Convert a long to a string in a provided buffer.
 *
 * @param n      The long to convert to a string
 * @param s      The buffer to build the string in. Should be
 *               long enough to hold as big a string as a
 *               negative long with a terminating zero can be.
 *
 * @return A pointer to the result of the conversion.
 */
char* itoaish(long n, char* s)
{
    int negative = 0;
    char* p = &s[11];
    if(0 > n)
    {
        negative = 1;
        n = -n;
    }
    *p = 0;
    if(!n)
    {
        *--p = '0';
    }
    while(n)
    {
        *--p = '0' + n % 10;
        n /= 10;
    }
    if(negative)
    {
        *--p = '-';
    }
    return p;
}

main()
{
    long n = -1234567890;
    char s[12];
    char* p = itoaish(n,s);
    printf("%s",p);
}
+1
source

All Articles