summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAnton Kling <anton@kling.gg>2023-11-01 19:34:42 +0100
committerAnton Kling <anton@kling.gg>2023-11-13 14:55:09 +0100
commit249d7f4ab0bff181534b0d17f3387f59b7c5feba (patch)
treebbd2aebe704041a086fc2104ae7a092a592b530e
parentec2ca84628a253eda95ccb097a2e269dc1dc47b8 (diff)
LibC: Support negative values in printf for %d
-rw-r--r--userland/libc/include/inttypes.h8
-rw-r--r--userland/libc/stdio/vfprintf.c24
-rw-r--r--userland/test/test.c6
3 files changed, 27 insertions, 11 deletions
diff --git a/userland/libc/include/inttypes.h b/userland/libc/include/inttypes.h
index adde7c8..9d53e83 100644
--- a/userland/libc/include/inttypes.h
+++ b/userland/libc/include/inttypes.h
@@ -5,10 +5,10 @@
#define PRId16 "d"
#define PRId32 "d"
#define PRId64 "d"
-#define PRIu8 "d"
-#define PRIu16 "d"
-#define PRIu32 "d"
-#define PRIu64 "d"
+#define PRIu8 "u"
+#define PRIu16 "u"
+#define PRIu32 "u"
+#define PRIu64 "u"
#define PRIx8 "x"
#define PRIx16 "x"
#define PRIx32 "x"
diff --git a/userland/libc/stdio/vfprintf.c b/userland/libc/stdio/vfprintf.c
index 79a22fb..f8d56ea 100644
--- a/userland/libc/stdio/vfprintf.c
+++ b/userland/libc/stdio/vfprintf.c
@@ -13,8 +13,6 @@ const char HEX_SET[0x10] = {'0', '1', '2', '3', '4', '5', '6', '7',
assert(0); \
*(int *)(_r) += _rc; \
}
-// if ((size_t)0 == _rc) \
-// assert(0); \
int fprint_num(FILE *f, int n, int base, char *char_set, int prefix,
int zero_padding, int right_padding) {
@@ -25,10 +23,22 @@ int fprint_num(FILE *f, int n, int base, char *char_set, int prefix,
}
char str[32];
int i = 0;
+
+ int is_signed = 0;
+
+ if (n < 0) {
+ is_signed = 1;
+ n *= -1;
+ }
+
for (; n != 0 && i < 32; i++, n /= base)
- // str[i] = (n % base) + '0';
str[i] = char_set[(n % base)];
+ if (is_signed) {
+ str[i] = '-';
+ i++;
+ }
+
char t = (zero_padding) ? '0' : ' ';
int orig_i = i;
@@ -175,10 +185,10 @@ int vfprintf(FILE *f, const char *fmt, va_list ap) {
break;
case 'i':
case 'd':
- if(-1 != precision) {
- zero_padding = 1;
- prefix = precision;
- right_padding = 0;
+ if (-1 != precision) {
+ zero_padding = 1;
+ prefix = precision;
+ right_padding = 0;
}
rc += fprint_int(f, va_arg(ap, int), prefix, zero_padding, right_padding);
cont = 0;
diff --git a/userland/test/test.c b/userland/test/test.c
index 041b08a..ca8c142 100644
--- a/userland/test/test.c
+++ b/userland/test/test.c
@@ -545,6 +545,12 @@ void printf_test(void) {
buf_n = sprintf(buf, "int: %00d", 1);
EXP("int: 1");
+ buf_n = sprintf(buf, "int: %d", -1337);
+ EXP("int: -1337");
+
+ buf_n = sprintf(buf, "int: %u", 1337);
+ EXP("int: 1337");
+
buf_n = sprintf(buf, "hex: %02x", 1);
EXP("hex: 01");
buf_n = sprintf(buf, "hex: %2x", 1);