Convert long integer(decimal) to base 36 string (strtol inverted function in C)

There’s no standard function for this. You’ll need to write your own one.

Usage example: https://godbolt.org/z/MhRcNA

const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

char *reverse(char *str)
{
    char *end = str;
    char *start = str;

    if(!str || !*str) return str;
    while(*(end + 1)) end++;
    while(end > start)
    {
        int ch = *end;
        *end-- = *start;
        *start++ = ch;
    }
    return str;
}

char *tostring(char *buff, long long num, int base)
{
    int sign = num < 0;
    char *savedbuff = buff;

    if(base < 2 || base >= sizeof(digits)) return NULL;
    if(buff)
    {
        do
        {   
            *buff++ = digits[abs(num % base)];
            num /= base;
        }while(num);
        if(sign)
        {
            *buff++ = '-';
        }
        *buff = 0;
        reverse(savedbuff);
    }
    return savedbuff;
}

Leave a Comment