Replacement For Itoa


Dimacus

Member
Joined
Jan 25, 2006
Messages
349
Age
37
Location
Land of the 'åäö'
Website
luminare.no-ip.org
I just got my gp2x today, so after a couple of emulator games, little doom and diffrent hello world programs,
I decided to try and port a gameengine I have been working on for about a year.

But then a problem arrised, I had been relying on itoa to convert char's containing numbers to int's.

Now as I tried to compile, i saw that the libaries that came with devkit does not have that function, or I have made a misstake when including the files.
(it should be within cstdlib or stdlib.h, but I cant find it there).

So, the question is; does anyone know of a replacement for the itoa function?

Thanks!

/Dimacus
 
But then a problem arrised, I had been relying on itoa to convert char's containing numbers to int's.

That's what atoi does, and atoi is portable. itoa does the opposite, but is not portable. sprintf is the only portable replacement for itoa, as far as I know:

Code:
char str[1024];
int number = 0xe1f23;
sprintf (str, "%d", number);

or use %x for hex. It can't do arbitrary bases (I think some variants of itoa can) - if you need that, you'll have to write your own function.
 
Hmm, just for fun, off the top of my head:

Code:
char *itoa (int num, char *str, int base)
{
    char *pos = str;
    int digit_value;

    if (num < 0) {
        *pos++ = '-';
        num = -num;
    }

    digit_value = 1;
    while (digit_value*base <= num) digit_value *= base;
    while (digit_value > 0) {
        int digit = num / digit_value;
        num -= digit * digit_value;
        *pos++ = '0' + digit;
        digit_value /= base;
    }
    *pos = '\0';
    return str;
}

Hope it works. :)
 
yeah, pretty much sprintf is your best bet. But I'd use snprintf instead.
 
Back
Top