From 9b777b088facde26c33df6c746b948caff725602 Mon Sep 17 00:00:00 2001 From: aqua Date: Fri, 1 Apr 2022 21:46:28 +0300 Subject: printf: add %d, %u and %x --- lib/string/itoa.c | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) (limited to 'lib/string') diff --git a/lib/string/itoa.c b/lib/string/itoa.c index 5eefb37..3708be2 100644 --- a/lib/string/itoa.c +++ b/lib/string/itoa.c @@ -1,13 +1,30 @@ -#include "string.h" +#include +#include + +static const char *numbers = "0123456789abcdef"; + +char * +itoa(char *p, int x, int base) +{ + const bool is_negative = (x < 0); + if (is_negative) x = -x; + + p = utoa(p, x, base); + + if (is_negative) *--p = '-'; + return p; +} char * -itoa(char *p, unsigned x) +utoa(char *p, unsigned x, int base) { - p += 3 * sizeof(int); - *--p = 0; + p += 3 * sizeof(unsigned); + *--p = '\0'; + do { - *--p = '0' + x % 10; - x /= 10; + *--p = numbers[x % base]; + x /= base; } while (x); + return p; } -- cgit v1.2.1