diff options
author | Ben Sima <ben@bsima.me> | 2018-06-29 20:09:42 -0700 |
---|---|---|
committer | Ben Sima <ben@bsima.me> | 2018-06-29 20:09:42 -0700 |
commit | 87f9f02d1fa62121173c33175a2107fbfb06ce30 (patch) | |
tree | adb3178e4fa916b2496d493d089b6b0ce2dea69f /xyo-networks/printf.c | |
parent | e81da383d908d4b7597cb73dc489f5162fcf19bf (diff) |
Prototype-quality printf
Needed help on the convert function
Diffstat (limited to 'xyo-networks/printf.c')
-rw-r--r-- | xyo-networks/printf.c | 91 |
1 files changed, 91 insertions, 0 deletions
diff --git a/xyo-networks/printf.c b/xyo-networks/printf.c new file mode 100644 index 0000000..4fa165c --- /dev/null +++ b/xyo-networks/printf.c @@ -0,0 +1,91 @@ +#include <stdio.h> +#include <stdarg.h> +#include "printf.h" + +/* + * my_printf("str: %s\nchr: %c\nhex: %x\nint: %d\noct: %o", + 1, 1, 1, 1, 1); +*/ + +int +main() +{ + my_printf("str: %s\nchr: %c\nhex: %x\nint: %d\noct: %o", + "hi", 'a', 0x32, 10, 8); + return 0; +} + +void +my_printf(char *format, ...) +{ + char *c; // a char in the `format` string + va_list args; + + va_start(args, format); + + for (c = format; *c != '\0'; c++) + { + while (*c != '%') + { + putchar(*c); + c++; + } + + c++; + + switch(*c) + { + case 'c': + { + putchar(va_arg(args, int)); + putchar('\n'); + break; + } + + case 'd': + { + puts(convert(va_arg(args, int), 10)); + break; + } + + case 'o': + { + puts(convert(va_arg(args, unsigned int), 8)); + break; + } + + case 'x': + { + puts(convert(va_arg(args, unsigned int), 16)); + break; + } + + case 's': + { + puts(va_arg(args, char*)); + break; + } + } + } + + va_end(args); +} + + +char* +convert(unsigned int num, int base) +{ + static char rep[]= "0123456789ABCDEF"; + static char buffer[50]; + char *ptr; + + ptr = &buffer[49]; + *ptr = '\0'; + + do { + *--ptr = rep[num%base]; + num /= base; + } while (num != 0); + + return(ptr); +} |