mescc: Fix itoa.

* lib/libc.c (itoa): Use function-static buffer.  Increase to 12 to
  handle INT_MIN.
  (itoab): Likewise.
This commit is contained in:
Jan Nieuwenhuizen 2018-05-20 08:33:06 +02:00
parent 03ba0e18df
commit 1dedd0ebca
No known key found for this signature in database
GPG Key ID: F3C1A0D9C1D65273
2 changed files with 31 additions and 28 deletions

View File

@ -91,28 +91,26 @@ atoi (char const *s)
return abtoi (&p, 0);
}
char itoa_buf[10];
char const*
itoa (int x)
{
//static char itoa_buf[10];
//char *p = buf+9;
char *p = itoa_buf;
p += 9;
static char itoa_buf[12];
char *p = itoa_buf + 11;
*p-- = 0;
//int sign = x < 0; // FIXME
int sign = 0;
if (x < 0) sign = 1;
if (sign)
x = -x;
unsigned u = x;
if (x < 0)
{
sign = 1;
u = -x;
}
do
{
*p-- = '0' + (x % 10);
x = x / 10;
} while (x);
*p-- = '0' + (u % 10);
u = u / 10;
} while (u);
if (sign && *(p + 1) != '0')
*p-- = '-';
@ -123,24 +121,24 @@ itoa (int x)
char const*
itoab (int x, int base)
{
//static char itoa_buf[10];
//char *p = buf+9;
char *p = itoa_buf;
p += 9;
static char itoa_buf[12];
char *p = itoa_buf + 11;
*p-- = 0;
//int sign = x < 0; // FIXME
int sign = 0;
if (x < 0) sign = 1;
if (sign)
x = -x;
unsigned u = x;
if (x < 0)
{
sign = 1;
u = -x;
}
do
{
int i = x % base;
int i = u % base;
*p-- = i > 9 ? 'a' + i - 10 : '0' + i;
x = x / base;
} while (x);
x = u / base;
} while (u);
if (sign && *(p + 1) != '0')
*p-- = '-';

View File

@ -30,16 +30,21 @@ test ()
puts ("\n");
puts ("t: itoa (33) == \"33\"\n");
if (strcmp (itoa (33), "33")) return 1;
if (strcmp (itoa (33), "33"))
return 1;
puts ("strcmp (itoa (-1), \"-1\")\n");
if (strcmp (itoa (-1), "-1")) return 1;
puts (itoa (-1));
if (strcmp (itoa (-1), "-1"))
return 2;
puts ("strcmp (itoa (0), \"0\")\n");
if (strcmp (itoa (0), "0")) return 1;
if (strcmp (itoa (0), "0"))
return 3;
puts ("strcmp (itoa (1), \"1\")\n");
if (strcmp (itoa (1), "1")) return 1;
if (strcmp (itoa (1), "1"))
return 4;
return 0;
}