Skip to content

Commit

Permalink
add hex support to ultoa
Browse files Browse the repository at this point in the history
  • Loading branch information
bemxio committed Sep 10, 2024
1 parent 8813167 commit a54742b
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 9 deletions.
12 changes: 6 additions & 6 deletions src/kernel/commands.c
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -66,7 +66,7 @@ void peek(char* token) {
: "ax", "si", "es"
);

ultoa(value, buffer);
ultoa(value, buffer, 10);
puts(buffer);

putchar('\r');
Expand Down Expand Up @@ -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(' ');
Expand Down Expand Up @@ -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('.');
Expand Down Expand Up @@ -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('.');
Expand Down
38 changes: 36 additions & 2 deletions src/kernel/lib/stdlib.c
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
}
2 changes: 1 addition & 1 deletion src/kernel/lib/stdlib.h
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit a54742b

Please sign in to comment.