G
gareth.p.davies
My latest version below.
#include <stdio.h>
#include <limits.h>
char * itoa(int a)
{
static char str[(size_t)((sizeof(int) * CHAR_BIT - 1) / 3.3) + 3];
int i = sizeof(str) - 1;
unsigned int abs_a = a;
int neg = 0;
if(a < 0)
{
neg = 1;
abs_a = -a ; //(1U - (1U + a));
}
do
{
str[--i] = '0' + abs_a % 10;
}
while ((abs_a = abs_a / 10) && i >= 0);
if(neg)
{
str[--i] = '-';
}
return &str;
}
int main(void)
{
char buffer[50];
sprintf(buffer, "%d", INT_MIN);
printf("sprintf 'says' %s\n", buffer);
sprintf(buffer, "%d", INT_MAX);
printf("sprintf 'says' %s\n", buffer);
puts(itoa(INT_MIN));
puts(itoa(INT_MAX));
puts(itoa(12));
puts(itoa(1));
puts(itoa(123));
return 0;
}
As I'm now using Michael's abs_a idea, I believe that I no longer need:
abs_a = (1U - (1U + a));
and that
abs_a = -a ;
is ok?
How does my function look now please? Any improvment ideas, or ideas
on how to reduce its size?
Thanks to all those that have been so willing to provide help.
gareth
#include <stdio.h>
#include <limits.h>
char * itoa(int a)
{
static char str[(size_t)((sizeof(int) * CHAR_BIT - 1) / 3.3) + 3];
int i = sizeof(str) - 1;
unsigned int abs_a = a;
int neg = 0;
if(a < 0)
{
neg = 1;
abs_a = -a ; //(1U - (1U + a));
}
do
{
str[--i] = '0' + abs_a % 10;
}
while ((abs_a = abs_a / 10) && i >= 0);
if(neg)
{
str[--i] = '-';
}
return &str;
}
int main(void)
{
char buffer[50];
sprintf(buffer, "%d", INT_MIN);
printf("sprintf 'says' %s\n", buffer);
sprintf(buffer, "%d", INT_MAX);
printf("sprintf 'says' %s\n", buffer);
puts(itoa(INT_MIN));
puts(itoa(INT_MAX));
puts(itoa(12));
puts(itoa(1));
puts(itoa(123));
return 0;
}
As I'm now using Michael's abs_a idea, I believe that I no longer need:
abs_a = (1U - (1U + a));
and that
abs_a = -a ;
is ok?
How does my function look now please? Any improvment ideas, or ideas
on how to reduce its size?
Thanks to all those that have been so willing to provide help.
gareth