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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
|
#include <stdarg.h>
#include <stdbool.h>
#include "uart.h"
static int print_decimal(unsigned long val)
{
char buf[32];
char *p = buf+31;
*p = 0;
if (val == 0)
*--p = '0';
else
{
do
{
unsigned long d, r;
/* Compiling with -Os results in a call to the division routine.
Do what the compiler ought to have done. */
d = __builtin_alpha_umulh(val, 0xcccccccccccccccd);
d >>= 3;
r = val - (d * 10);
*--p = r + '0';
val = d;
}
while (val);
}
uart_puts(COM1, p+1);
return sizeof(buf) - (p - buf);
}
static int print_hex(unsigned long val)
{
char buf[32];
char *p = buf+31;
*p = 0;
if (val == 0)
*--p = '0';
else
{
do
{
int d = val % 16;
*--p = (d < 10 ? '0' : 'a' - 10) + d;
val /= 16;
}
while (val);
}
uart_puts(COM1, p+1);
return sizeof(buf) - (p - buf);
}
int printf(const char *fmt, ...)
{
va_list args;
unsigned long val;
int r = 0;
va_start(args, fmt);
for (; *fmt ; fmt++)
if (*fmt != '%')
{
uart_putchar(COM1, *fmt);
r++;
}
else
{
bool is_long = false;
restart:
switch (*++fmt)
{
case '%':
uart_putchar(COM1, '%');
r++;
break;
case 'l':
is_long = true;
goto restart;
case 'd':
if (is_long)
{
long d = va_arg (args, long);
if (d < 0)
{
uart_putchar(COM1, '-');
d = -d;
}
val = d;
}
else
{
int d = va_arg (args, int);
if (d < 0)
{
uart_putchar(COM1, '-');
d = -d;
r++;
}
val = d;
}
goto do_unsigned;
case 'u':
if (is_long)
val = va_arg (args, unsigned long);
else
val = va_arg (args, unsigned int);
do_unsigned:
r += print_decimal (val);
break;
case 'x':
if (is_long)
val = va_arg (args, unsigned long);
else
val = va_arg (args, unsigned int);
r += print_hex (val);
case 's':
{
const char *s = va_arg (args, const char *);
while (*s)
{
uart_putchar(COM1, *s++);
r++;
}
break;
}
default:
uart_putchar(COM1, '%');
uart_putchar(COM1, *fmt);
r += 2;
break;
}
}
va_end(args);
return r;
}
|