Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

base64

strtol

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?

like image 880
Łukasz Przeniosło Avatar asked Jan 15 '20 12:01

Łukasz Przeniosło


People also ask

What does strtol mean in c?

The strtol library function in C converts a string to a long integer. The function works by ignoring any whitespace at the beginning of the string, converting the next characters into a long integer, and stopping when it comes across the first non-integer character.

Does strtol change the string?

The strtoll() function converts a character string to a long long integer value. The parameter nptr points to a sequence of characters that can be interpreted as a numeric value of type long long int.


1 Answers

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;
}
like image 160
0___________ Avatar answered Sep 30 '22 09:09

0___________