Skip to content

Commit

Permalink
Fix itoa bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
maximecb committed Nov 10, 2023
1 parent f6496a9 commit 868f1fb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
15 changes: 12 additions & 3 deletions ncc/include/stdlib.h
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 7 additions & 0 deletions ncc/tests/stdlib.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 868f1fb

Please sign in to comment.