summaryrefslogtreecommitdiff
path: root/xyo-networks/printf.c
blob: bef45ab6f6e6d9439217a64e216f429f5af93a30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdio.h>
#include <stdarg.h>
#include "printf.h"

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); 
}