printf函数的实现

来源:互联网 发布:java里面微积分怎么用 编辑:程序博客网 时间:2024/05/16 08:14

    printf函数是C语言库函数中的输出函数。在学习STM32过程用由于需要用到串口打印功能,但是程序原来的printf函数打印到串口时,出现了大量乱码。无奈只能自己研究一下printf函数的构成。写个一个简化版的printf函数。

int myprintf(const char *format, ...){    va_list ap;    int val,r_val;    double val_double;  int val_double_integ, temp_double;  double val_double_dec;char count,ch;char *s = NULL; int res = 0;//返回值    RS485SEND;    va_start(ap,format);//初始化ap    while('\0' != *format)//str为字符串,它的最后一个字符肯定是'\0'(字符串的结束符)  {    switch(*format){case '%': format++;{switch(*format){case 'd'://十进制输出{val = va_arg(ap,int);r_val = val;count = 0;if (r_val == 0){    count = 1;}while(r_val){count++;r_val /= 10;}res += count;//返回值长度增加   r_val = val;while(count){ch = r_val / mypow(10,count - 1);r_val %= mypow(10,count - 1);myputchar(ch + '0');                           //数字转成字符count--;}}break;case 'x':{val = va_arg(ap,int);r_val = val;count = 0;  if (r_val == 0){    count = 1;}while(r_val) {    count++; //整数的长度    r_val /= 16;   }res += count;r_val = val;while(count)   {   ch = r_val / mypow(16, count - 1);   r_val %= mypow(16, count - 1);if(ch <= 9)myputchar(ch + '0');//数字到字符的转换   else   //数字转成字符   10~a 11~b 12~c ...myputchar(ch - 10 + 'a');   count--; }}break;case 'l':{}break;case 'f':{    val_double = va_arg(ap,double);  count = 0;  val_double_integ = (int) val_double;  val_double_dec = val_double - val_double_integ;  /*整数部分打印*/  if (val_double_integ == 0){    count = 1;}while(val_double_integ){    count++;  val_double_integ /= 10;  }res += count;//返回值长度增加     val_double_integ = (int) val_double;while(count){  ch = val_double_integ / mypow(10, count - 1);   val_double_integ %= mypow(10, count - 1);  myputchar(ch + '0');  //数字到字符的转换       count--;}/*打印小数点*/myputchar('.');res += 1;//返回值长度增加   /*打印小数部分,小数点后六位强制清零*/count = 0;temp_double = 0;if((val_double_dec - temp_double) == 0){    count = 1;}  while((val_double_dec - temp_double)&&(count < 6)){  val_double_dec *= 10;  temp_double = (int)val_double_dec;  count++;}res += count;//返回值长度增加   while(count){  ch = temp_double / mypow(10, count - 1);   temp_double %= mypow(10, count - 1);  myputchar(ch + '0');  //数字到字符的转换       count--;}}break;case 's': //发送字符串  {s = va_arg(ap, char *);mypustr(s);//字符串,返回值为字符指针   res += strlen(s);//返回值长度增加}break;   case 'c':   {myputchar( (char)va_arg(ap, int )); //大家猜为什么不写char,而要写int   res += 1;}break;  default :;}  }break;case '\n':{    myputchar('\n');  res += 1;}break;case '\r':{    myputchar('\r');  res += 1;}break;default :                           //显示原来的参数字符串{    myputchar(* format);  res += 1;}}format++;  }va_end(ap);RS485RECE;  return res;}


原创粉丝点击