Page 1 of 1

Convert Number

Posted: Wed Jun 18, 2003 10:12 am
by Fresh
Hi,

I'm looking for the fastest algorithm to convert an unsigned int to string in format x,x,x,x,x. Thanks...

Code: Select all


void convert(unsigned int, char *buf)
{
    // need help
    ....
    ....
    ....
}

void main()
{
    char buf[1024];
    unsigned int x = 2123456;

    convert(x, buf);
    printf("%s\n", buf);    // buf = 2,123,456
}
- novice :-?

Posted: Wed Jun 18, 2003 3:13 pm
by Adil
hi. i would try with the following.

Code: Select all

void convert(unsigned int  val, char *out)
{
    char str[15], *s = str;
    int len=0;

    if(!val)
    {
        *out++ = '0';
        *out = 0;
        return;
    }

    while(val)
    {
        if(len%3 == 0 && len)
        {
            *s++ = ',';
        }
        *s++ = val%10 + '0';
        val /= 10;
        len++;
    }

    while(--s >= str)
    {
        *out++ = *s;
    }
    *out = 0;
}
i would like to know of a faster procedure.

...

Posted: Tue Jul 01, 2003 3:56 am
by Fresh
Thanks....

- novice :wink: