G
gareth.p.davies
Hi.
Just as a learning exercise, I've come up with an implementation of
itoa() without using something like sprintf. However, I can't figure
out how to extend it to deal with negative numbers - any help
appreciated!
char * itoa(int a)
{
#define BUFFSIZE 50
static char str[BUFFSIZE];
int i = sizeof(str) - 1;
do
{
str[--i] = '0' + a % 10;
}
while ((a = a / 10) && i >= 0);
return &str;
}
Couple of notes on this.
I didn't want to have to pass in a char * to a buffer, so I return a
pointer to a char in the static buffer - I think 50, although chosen
arbitrarily, should be big enough. I did think my making this exact
for the implementation, and toyed with the idea of somehow using
MAX_INT in limits.h to do this. However, I couldn't figure that out,
e.g., I thought of stringifying MAX_INT and then using sizeof on it,
but I don't think I can do that as a pre-processor thing and I can't
think of any other way to do this.
Related. Where I #define BUFFSIZE, I'm not sure that this is good - for
example, if this source is included in a project in which there's
already a #define BUFFSIZE something, will my #define cause a problem,
if so, how can I avoid that, e.g., just use a const instead?
I also didn't/don't feel I can implement a 'radix' parameter - so I
left that out.
Thanks,
gareth
Just as a learning exercise, I've come up with an implementation of
itoa() without using something like sprintf. However, I can't figure
out how to extend it to deal with negative numbers - any help
appreciated!
char * itoa(int a)
{
#define BUFFSIZE 50
static char str[BUFFSIZE];
int i = sizeof(str) - 1;
do
{
str[--i] = '0' + a % 10;
}
while ((a = a / 10) && i >= 0);
return &str;
}
Couple of notes on this.
I didn't want to have to pass in a char * to a buffer, so I return a
pointer to a char in the static buffer - I think 50, although chosen
arbitrarily, should be big enough. I did think my making this exact
for the implementation, and toyed with the idea of somehow using
MAX_INT in limits.h to do this. However, I couldn't figure that out,
e.g., I thought of stringifying MAX_INT and then using sizeof on it,
but I don't think I can do that as a pre-processor thing and I can't
think of any other way to do this.
Related. Where I #define BUFFSIZE, I'm not sure that this is good - for
example, if this source is included in a project in which there's
already a #define BUFFSIZE something, will my #define cause a problem,
if so, how can I avoid that, e.g., just use a const instead?
I also didn't/don't feel I can implement a 'radix' parameter - so I
left that out.
Thanks,
gareth