Pergunta

I am trying to use 'user434507''s unsigned solution here:

C++ performance challenge: integer to std::string conversion

but instead I want it to return a char * and not accept in a string.

I have been playing around with it for awhile and this is what I have got, but it just returns nothing/garbage - My limited C and pointer knowledge is not helping me. I think I am using malloc right, but in his original code it's as if he uses an internal char* and just changed the elements of a string and returns the string. I figured if I allocated via malloc it would have the same effect :

char * itostr(unsigned val)
{

    const char digit_pairs[201] = {
      "00010203040506070809"
      "10111213141516171819"
      "20212223242526272829"
      "30313233343536373839"
      "40414243444546474849"
      "50515253545556575859"
      "60616263646566676869"
      "70717273747576777879"
      "80818283848586878889"
      "90919293949596979899"
    };

    int size;
    if(val>=10000) {
        if(val>=10000000) {
            if(val>=1000000000) {
                size=10;
            } else if(val>=100000000) {
                size=9;
            } else {
                size=8;
            }
        } else {
            if(val>=1000000) {
                size=7;
            } else if(val>=100000) {
                size=6;
            } else {
                size=5;
            }
        }
    } else {
        if(val>=100) {
            if(val>=1000) {
                size=4;
            } else {
                size=3;
            }
        } else {
            if(val>=10) {
                size=2;
            } else {
                size=1;
            }
        }
    }

    char * c = (char *)malloc(size + 1);
    c[size] = '\0';

    //char* c = &s[size-1];
    while(val>=100)
    {
       int pos = val % 100;
       val /= 100;
       *(short*)(c-1)=*(short*)(digit_pairs+2*pos); 
       c-=2;
    }
    while(val>0)
    {
        *c--='0' + (val % 10);
        val /= 10;
    }


    return c;
}
Foi útil?

Solução

c += size-1;

You need this line just before the first while loop. The two loops write the digits from right to left. It's needed so that writing starts at the right end of the string.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top