printf函数源码linux,再来一版简易的printf函数实现

以前发过两版简易的串口printf函数实现,最近搞了一段时间Linux的库文件,回过头又有不同的理解。

这一版函数基于MSP430F169,%d %x %o %b的实现不再由自己编写函数,而是调用MSP430-GCC的标准库函数:

#include

char *itoa(int num, char *str, int radix);

send_fun函数指针,指向调用的UARTx的字节发送函数:

void uart_printf(send_fun fun, char *fmt, ...)

{

char *pnt = (char *)&fmt + sizeof(fmt);

char *str, buf[9];

int radix;

while (*fmt != '\0') {

if (*fmt != '%') {

fun(*fmt);

fmt += 1;

continue;

}

switch (*(fmt + 1)) {

case 'c':

fun(*((int *)pnt));

pnt += sizeof(int);

fmt += 2;

continue;

case 's':

str = (char *)*((int *)pnt);

while (*str != '\0')

fun(*str++);

pnt += sizeof(int);

fmt += 2;

continue;

case 'd':

radix = 10;

goto SEND_NUM;

case 'x':

radix = 16;

goto SEND_NUM;

case 'o':

radix = 8;

goto SEND_NUM;

case 'b':

radix = 2;

goto SEND_NUM;

SEND_NUM:

str = itoa(*(int *)pnt, buf, radix);

while (*str != '\0')

fun(*str++);

pnt += sizeof(int);

fmt += 2;

continue;

default:

break;

}

}

}

实际上,库stdio.h中也提供了printf的实现,直接调用它们就可以了:

int __attribute__((format (printf, 2, 3))) uprintf(int (*func)(int c), const char *fmt, ...);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值