简易printf打印实现,占用内存非常小------<嵌入式开发自学笔记>

来源:互联网 发布:淘宝洗纹身精油骗局 编辑:程序博客网 时间:2024/05/22 11:42
//打印单个字符void print_ch(const char ch){//这里实现你的串口发送单个字符的函数  // LPUART_WriteBlocking(LPUART0, (uint8_t *)&ch, 1);}//打印整数,不明白的可以网上查查,怎么回事,print_int()又调用了print_int()void print_int(int dec){    if(dec < 0)    {        print_ch('-');        dec = -dec;    }    if(dec / 10)        print_int(dec / 10);    print_ch(dec%10 + '0');}//转换成十六进制static void get_hex(uint8_t hex){    const uint8_t ascii_zero = 48;    const uint8_t ascii_a = 65;    if ((hex >= 0) && (hex <= 9))    {        print_ch(hex + ascii_zero);    }    if ((hex >= 10) && (hex <= 15))    {        print_ch(hex - 10 + ascii_a);    }}//以十六进制格式输出void print_hex(uint32_t hex){    if(hex / 16)        print_hex(hex/16);    get_hex(hex%16);}//打印字符串void print_str(const char *ptr){    while(*ptr)    {        print_ch(*ptr);        ptr++;    }}//打印浮点void print_float(const float flt){    int tmpint = (int)flt;    int tmpflt = (int)(100000 * (flt - tmpint));    if(tmpflt % 10 >= 5)    {        tmpflt = tmpflt / 10 + 1;    }    else    {        tmpflt = tmpflt / 10;    }    print_int(tmpint);    print_ch('.');    print_int(tmpflt);}//带格式打印,void my_printf(const char *format,...){    va_list ap;    va_start(ap,format);    while(*format)    {        if(*format != '%')        {            print_ch(*format);            format++;        }        else        {            format++;            switch(*format)            {            case 'c':            {                char valch = va_arg(ap,int);                print_ch(valch);                format++;                break;            }            case 'd':            {                int valint = va_arg(ap,int);                print_int(valint);                format++;                break;            }            case 's':            {                char *valstr = va_arg(ap,char *);                print_str(valstr);                format++;                break;            }            case 'f':            {                float valflt = va_arg(ap,double);                print_float(valflt);                format++;                break;            }            case 'x':            case 'X':            {                int valhex = va_arg(ap,int);                if(((uint32_t)valhex)<16)                {                    print_ch('0');                }                print_hex((uint32_t)valhex);                format++;                break;            }            default:            {                print_ch(*format);                format++;            }            }        }    }    va_end(ap);}