Search code examples
cconstants

convert integer variable into string in C language using malloc in dynamic string to store


In C language i want to store the value of variable integer to another variable as string. How can i achieve this?

Example :

int num1 = 123456789;

I want to store the value of num1 as string in another variable.


Solution

  • If you are required avoid to a 2 pass conversion of first finding the string size needed and then allocating the size, consider a 1 step approach that starts with a worst case size.


    To form a string, first determine the maximum size of character array needed.

    Number of decimal digits can be approximated with knowing the number of binary value bits in an int or sizeof(int)*CHAR_BIT - 1 scaled by log102 or 0.301...., which is just less than 28/93*1.

    Thus the digits needed is not more than (sizeof(int)*CHAR_BIT - 1)*28/93 + 1. Adding 1 for the potential sign bit and 1 for the null character, we arrive at:

    #define LOG10_2_N 28
    #define LOG10_2_D 93
    #define INT_STRING_SIZE ((sizeof(int)*CHAR_BIT - 1)*LOG10_2_N/LOG10_2_D + 3) 
    char buf[INT_STRING_SIZE];
    

    Now print into that.

    int len = snprintf(buf, sizeof buf, "%d", num1);
    assert (len > 0 && (unsigned) len < sizeof buf);
    // Allocate a copy if desired.
    return strdup(buf);
    

    *1 Rare encoding will also have padding bits, yet that only makes our buffer size a tad too high. Rarely is this a concern.