From 4512a9324973caa7f7eb3e57591d29f1eee3c22f Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Thu, 26 Jun 2025 04:23:31 +0200 Subject: [PATCH] First draft of a kernel side library, string.h & string.c implementing itoa --- lib/string.c | 39 +++++++++++++++++++++++++++++++++++++++ lib/string.h | 7 +++++++ 2 files changed, 46 insertions(+) create mode 100644 lib/string.c create mode 100644 lib/string.h diff --git a/lib/string.c b/lib/string.c new file mode 100644 index 0000000..7647d1f --- /dev/null +++ b/lib/string.c @@ -0,0 +1,39 @@ +char *itoa(int value, char *str, int base) { + char *p = str; + char *p1, *p2; + unsigned int uvalue = value; + int negative = 0; + + if (base < 2 || base > 36) { + *str = '\0'; + return str; + } + + if (value < 0 && base == 10) { + negative = 1; + uvalue = -value; + } + + // Convert to string + do { + int digit = uvalue % base; + *p++ = (digit < 10) ? '0' + digit : 'a' + (digit - 10); + uvalue /= base; + } while (uvalue); + + if (negative) + *p++ = '-'; + + *p = '\0'; + + // Reverse string + p1 = str; + p2 = p - 1; + while (p1 < p2) { + char tmp = *p1; + *p1++ = *p2; + *p2-- = tmp; + } + + return str; +} diff --git a/lib/string.h b/lib/string.h new file mode 100644 index 0000000..ceeb2a8 --- /dev/null +++ b/lib/string.h @@ -0,0 +1,7 @@ +#ifndef KERNEL_STRING_H +#define KERNEL_STRING_H + +/** Integer to ascii */ +char *itoa(int value, char *str, int base); + +#endif