#include <stdio.h>
typedef char *va_list;
#define __va_rounded_size(TYPE) \
(((sizeof(TYPE)+sizeof(int)-1)/sizeof(int))*sizeof(int))
#define va_start(AP, LASTARG) \
(AP=((char *)&(LASTARG)+__va_rounded_size(LASTARG)))
#define va_end(AP) ((va_list)0)
#define va_arg(AP, TYPE) \
(AP+=__va_rounded_size(TYPE), \
*((TYPE *)(AP-__va_rounded_size(TYPE))))
int myprintf(char *buf, char *fmt, ...);
void itoa(int num, char *buf, unsigned int base);
unsigned int div(unsigned int *n, unsigned int b);
int main(void) {
char buf[0x100];
myprintf(buf, "%%%%%% %b %b %b %b %b %b %b %b ###", \
128, 64, 32, 16, 8, 4, 2, 1);
printf("%s\n", buf);
myprintf(buf, "%%%%%% %b %b %b %b ###", \
0x8000, 0x4000, 0x2000, 0x1000);
printf("%s\n", buf);
myprintf(buf, "%%%%%% %b %b %b %b ###", \
0x800, 0x400, 0x200, 0x100);
printf("%s\n", buf);
return 1;
}
int myprintf(char *buf, char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
char buf1[64], *temp1;
int d;
char *s, c;
while (*fmt) {
if (*fmt == '%') {
++fmt;
switch (*fmt) {
case '%':
*buf++ = '%';
fmt++;
break;
case 's':
s = (char *)va_arg(ap, char *);
while(*s)
*buf++ = *s++;
fmt++;
break;
case 'c':
c = (char)va_arg(ap, char);
*buf++ = c;
fmt++;
break;
case 'd':
d = (int)va_arg(ap, int);
itoa(d, buf1, 10);
temp1 = buf1;
while (*temp1) {
*buf++ = *temp1++;
}
fmt++;
break;
case 'x':
d = (int)va_arg(ap, int);
*buf++ = '0';
*buf++ = 'x';
itoa(d, buf1, 16);
temp1 = buf1;
while (*temp1) {
*buf++ = *temp1++;
}
fmt++;
break;
case 'b':
d = (int)va_arg(ap, int);
itoa(d, buf1, 2);
temp1 = buf1;
while (*temp1) {
*buf++ = *temp1++;
}
fmt++;
*buf++ = 'b';
break;
}
} else {
*buf++ = *fmt++;
}
}
va_end(ap);
*buf = '\0';
return 1;
}
unsigned int div(unsigned int *n, unsigned int b) {
int res;
res = *n % b;
*n = *n / b;
return res;
}
void itoa(int num, char *buf, unsigned int base) {
char digits[16] = "0123456789abcdef";
char temp[64];
int i = 0;
while (num)
*(temp + i++) = digits[div(&num, base)];
while (i-- > 0)
*buf++ = *(temp + i);
*(buf) = '\0';
return;
}
mysprintf函数,不断为操作系统开发加油(只是加入了二进制数的显示)
猜你喜欢
转载自blog.csdn.net/weixin_39410618/article/details/82825725
今日推荐
周排行