操作系统开发中printf函数的简单实现

虽然没有一行注释,相信研究方向是操作系统的你也能够看懂吧,是啊,它实在是太傻太天真了,我真的希望自己的代码很慌很保利! 

 

// printf.c
#include "stdio.h"

unsigned int strlen_(const char* s);
unsigned int div_(unsigned int* i, unsigned int n);
void i2a(char* buf, unsigned int a, unsigned int b);
int vsprintf_(char* buf, const char* format_s, char* temp);
int printf_(const char* format_s, ...);


int main(void) {
	printf_(" %%% %%%% %c %s %d %% %x %b ",
	'L', "Hello, World!...", 0xff, 256, 65535);	
}

unsigned int strlen_(const char* s) {
	const char* t = s;
	while(*t) {
		t++;
	}
	return t - s;
}

unsigned int div_(unsigned int* i, unsigned int n) {
	unsigned int res = *i % n;
	*i /= n;
	return res;
}

void i2a(char* buf, unsigned int a, unsigned int b) {
	char* res = buf, * p;
	if(!a) {
		*res++ = '0';
		*res = '\0';
		return;
	}
	const char num[32] = "0123456789abcdef";
	char t[0x100];
	p = t;
	while(a) {
		*p++ = num[div_(&a, b)];
	}
	*p = '\0';
	while(p != t - 1) {
		*res++ = *--p;
	}
	*res = '\0';
}

int vsprintf_(char* buf, const char* format_s, char* temp) {
	const char* s = format_s;
	char t[0x100], * p, * res = buf;
	unsigned int i;
	while(*s) {
		if(*s == '%') {
			s++;
			switch(*s) {
			case '%':
				*buf++ = *s;
				break;
			case 'c':
				i = *((char*)(temp+=4));
				*buf++ = (char)i;
				break;
			case 's':
				p = *((char**)(temp+=4));
				while(*p) {
					*buf++ = *p++;
				}
				break;
			case 'd':
				i = *((int*)(temp+=4));
				i2a(t, i, 10);
				p = t;
				while(*p) {
					*buf++ = *p++;
				}
				break;
			case 'x':
				i = *((int*)(temp+=4));
				i2a(t, i, 16);
				*buf++ = '0';
				*buf++ = 'x';
				p = t;
				while(*p) {
					*buf++ = *p++;
				}				
				break;
			case 'b':
				i = *((int*)(temp+=4));
				i2a(t, i, 2);
				p = t;
				while(*p) {
					*buf++ = *p++;
				}
				*buf++ = 'b';
				break;
			}
			s++;
		} else {
			*buf++ = *s++;
		}
	}
	*buf = '\0';
	return strlen_(res);
}

int printf_(const char* format_s, ...) {
	char t[0x400];
	char* temp = (char*)&format_s;
	vsprintf_(t, format_s, temp);
	temp = NULL;
	unsigned int i = 0;
	while(t[i]) {
		printf("%c", t[i++]);
	}
	return i;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_39410618

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值