From a54742b2ff5483f8fd1d0221acd9ae3faf4d462e Mon Sep 17 00:00:00 2001 From: bemxio Date: Tue, 10 Sep 2024 15:29:15 +0200 Subject: [PATCH] add hex support to ultoa --- src/kernel/commands.c | 12 ++++++------ src/kernel/lib/stdlib.c | 38 ++++++++++++++++++++++++++++++++++++-- src/kernel/lib/stdlib.h | 2 +- 3 files changed, 43 insertions(+), 9 deletions(-) diff --git a/src/kernel/commands.c b/src/kernel/commands.c index e27ce13..6a588ba 100644 --- a/src/kernel/commands.c +++ b/src/kernel/commands.c @@ -54,7 +54,7 @@ void peek(char* token) { unsigned int offset = address & 0xffff; unsigned char value; - char* buffer; + char buffer[4]; __asm__ ( "movw %1, %%ax\n" @@ -66,7 +66,7 @@ void peek(char* token) { : "ax", "si", "es" ); - ultoa(value, buffer); + ultoa(value, buffer, 10); puts(buffer); putchar('\r'); @@ -212,13 +212,13 @@ void _int(char* token) { :: "ax", "bx", "cx", "dx", "si", "di" ); - char* buffer; + char buffer[7]; for (unsigned char i = 0; i < 6; i++) { puts(names[i]); putchar('='); - ultoa(registers[i], buffer); + ultoa(registers[i], buffer, 16); puts(buffer); putchar(' '); @@ -298,7 +298,7 @@ void read(char* token) { if (status != 0) { puts("Disk read failed with error code "); - ultoa(status, token); + ultoa(status, token, 16); puts(token); putchar('.'); @@ -377,7 +377,7 @@ void write(char* token) { if (status != 0) { puts("Disk write failed with error code "); - ultoa(status, token); + ultoa(status, token, 16); puts(token); putchar('.'); diff --git a/src/kernel/lib/stdlib.c b/src/kernel/lib/stdlib.c index ddc850c..e0c4076 100644 --- a/src/kernel/lib/stdlib.c +++ b/src/kernel/lib/stdlib.c @@ -65,8 +65,8 @@ unsigned long atoul(const char* nptr) { return __atoul_dec(nptr); } -char* ultoa(unsigned long n, char* buf) { - int i = 0; +char* __ultoa_dec(unsigned long n, char* buf) { + unsigned char i = 0; if (n == 0) { buf[i++] = '0'; @@ -80,4 +80,38 @@ char* ultoa(unsigned long n, char* buf) { strrev(buf); return buf; +} + +char* __ultoa_hex(unsigned long n, char* buf) { + unsigned char i = 0; + + if (n == 0) { + buf[i++] = '0'; + } else { + for (unsigned long x = n; x > 0; x /= 16) { + unsigned long r = x % 16; + + if (r < 10) { + buf[i++] = r + 48; + } else { + buf[i++] = r + 55; + } + } + } + + buf[i++] = 'x'; + buf[i++] = '0'; + buf[i] = '\0'; + + return strrev(buf); +} + +char* ultoa(unsigned long n, char* buf, char base) { + if (base == 10) { + return __ultoa_dec(n, buf); + } else if (base == 16) { + return __ultoa_hex(n, buf); + } + + return NULL; } \ No newline at end of file diff --git a/src/kernel/lib/stdlib.h b/src/kernel/lib/stdlib.h index fb7503d..d03da76 100644 --- a/src/kernel/lib/stdlib.h +++ b/src/kernel/lib/stdlib.h @@ -4,6 +4,6 @@ #include "string.h" unsigned long atoul(const char* nptr); -char* ultoa(unsigned long n, char* buf); +char* ultoa(unsigned long n, char* buf, char base); #endif \ No newline at end of file