cbase64strtol

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


I can use the strtol function for turning a base36 based value (saved as a string) into a long int:

long int val = strtol("ABCZX123", 0, 36);

Is there a standard function that allows the inversion of this? That is, to convert a long int val variable into a base36 string, to obtain "ABCZX123" again?


Solution

  • 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;
    }