Skip to content

Commit

Permalink
Implement integer format specifiers
Browse files Browse the repository at this point in the history
  • Loading branch information
alanjian85 committed Mar 30, 2024
1 parent 062b298 commit cce35f6
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 6 deletions.
2 changes: 1 addition & 1 deletion include/types.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ typedef int32_t i32;
typedef int64_t i64;

typedef uintptr_t usize;
typedef uintptr_t ssize;
typedef intptr_t ssize;

#endif // TYPES_H_
1 change: 1 addition & 0 deletions src/kmain.c
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include <attribs.h>
#include <kprintf.h>
#include <limits.h>
#include <types.h>

noreturn void kmain(void) {
Expand Down
70 changes: 65 additions & 5 deletions src/kprintf.c
Original file line number Diff line number Diff line change
@@ -1,7 +1,50 @@
#include <stdarg.h>

#include <types.h>
#include <uart.h>

static void print_usize(usize val, i32 radix) {
if (val == 0) {
uart_putc('0');
return;
}

char buf[(usize) (sizeof(val) * 8.0 / 3 + 1)];
usize pos = sizeof(buf);

while (val != 0) {
pos--;
u8 digit = val % radix;
if (digit < 10)
buf[pos] = digit + '0';
else
buf[pos] = digit - 10 + 'a';
val /= radix;
}

for (usize i = pos; i < sizeof(buf); i++)
uart_putc(buf[i]);
}

static void print_ssize(ssize val, i32 radix) {
if (val < 0) {
uart_putc('-');
val = -val;
}

print_usize(val, radix);
}

static void print_ptr(void *ptr) {
for (usize i = sizeof(ptr) * 2; i > 0; i--) {
u8 nibble = (usize) ptr >> ((i - 1) * 4) & 0xF;
if (nibble < 10) {
uart_putc(nibble + '0');
} else {
uart_putc(nibble - 10 + 'a');
}
}
}

void kprintf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
Expand All @@ -16,17 +59,34 @@ void kprintf(const char *fmt, ...) {
fmt++;

switch (*fmt++) {
case 'c': {
char c = va_arg(args, int);
uart_putc(c);
case '%':
uart_putc('%');
break;
case 'c':
uart_putc(va_arg(args, int));
break;
}
case 's': {
const char *s = va_arg(args, const char *);
for (; *s; s++)
uart_putc(*s);
break;
}
case 'd':
case 'i':
print_ssize(va_arg(args, int), 10);
break;
case 'o':
print_usize(va_arg(args, unsigned), 8);
break;
case 'x':
print_usize(va_arg(args, unsigned), 16);
break;
case 'u':
print_usize(va_arg(args, unsigned), 10);
break;
case 'p':
print_ptr(va_arg(args, void *));
break;
}
}

Expand Down

0 comments on commit cce35f6

Please sign in to comment.