簡易printf打印實現,佔用內存非常小------

//打印單個字符
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);
}













發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章