diff --git a/ncc/include/stdlib.h b/ncc/include/stdlib.h index 08be9a5..e1caf9e 100644 --- a/ncc/include/stdlib.h +++ b/ncc/include/stdlib.h @@ -21,13 +21,22 @@ char* itoa(int value, char* str, int base) { assert(base > 0 && base <= 16); + // If negative, write a minus sign + if (value < 0) + { + *str = '-'; + ++str; + value = -value; + } + // Compute the number of digits int num_digits = 0; - for (int n = value; n > 0; n = n / base) + int n = value; + do { - int digit = value % base; + n = n / base; ++num_digits; - } + } while (n > 0); // The digits have to be written in reverse order for (int i = num_digits - 1; i >= 0; --i) diff --git a/ncc/tests/stdlib.c b/ncc/tests/stdlib.c index 321b565..6131eac 100644 --- a/ncc/tests/stdlib.c +++ b/ncc/tests/stdlib.c @@ -32,6 +32,13 @@ void main() assert(buf[0] == '1' && buf[1] == '7' && buf[2] == 0); itoa(15, buf, 16); assert(buf[0] == 'F' && buf[1] == 0); + itoa(-77, buf, 10); + assert(buf[0] == '-'); + assert(buf[1] == '7'); + assert(buf[2] == '7'); + itoa(0, buf, 10); + assert(buf[0] == '0'); + assert(buf[1] == '\0'); // Test the exit function exit(0);