Skip to content

Commit

Permalink
Add itoa() to stdlib.h
Browse files Browse the repository at this point in the history
  • Loading branch information
maximecb committed Nov 10, 2023
1 parent 37de9b8 commit f6496a9
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
37 changes: 37 additions & 0 deletions ncc/include/stdlib.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#define __STDLIB_H__

#include <stddef.h>
#include <assert.h>

int abs(int n)
{
Expand All @@ -15,6 +16,42 @@ void exit(int status)
asm (status) -> void { exit; };
}

// Convert integer to string
char* itoa(int value, char* str, int base)
{
assert(base > 0 && base <= 16);

// Compute the number of digits
int num_digits = 0;
for (int n = value; n > 0; n = n / base)
{
int digit = value % base;
++num_digits;
}

// The digits have to be written in reverse order
for (int i = num_digits - 1; i >= 0; --i)
{
int digit = value % base;
value = value / base;

char ch;
if (digit < 10)
{
ch = '0' + digit;
}
else
{
ch = 'A' + (digit - 10);
}

str[i] = ch;
}

// Write the null terminator
str[num_digits] = '\0';
}

// We define RAND_MAX to be the same as INT32_MAX
#define RAND_MAX 0x7FFFFFFF

Expand Down
12 changes: 11 additions & 1 deletion ncc/tests/stdlib.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#include <stdlib.h>
#include <assert.h>

char buf[32];

void main()
{
assert(abs(-5) == 5);
Expand All @@ -16,13 +18,21 @@ void main()
}

// Check that at least one value is positive
while (true)
while (1)
{
int r = rand();
if (r > 10)
break;
}

// Test itoa function
itoa(5, buf, 10);
assert(buf[0] == '5' && buf[1] == 0);
itoa(17, buf, 10);
assert(buf[0] == '1' && buf[1] == '7' && buf[2] == 0);
itoa(15, buf, 16);
assert(buf[0] == 'F' && buf[1] == 0);

// Test the exit function
exit(0);
}

0 comments on commit f6496a9

Please sign in to comment.