简体   繁体   English

Sprintf比打印占用更多的空间?

[英]Sprintf takes more space than print?

I'm doing an Arduino sketch and I'm trying to gain some space. 我正在做一个Arduino草图,我正在尝试获得一些空间。 I saw on some websites that it's better to use sprintf than print . 我在一些网站上看到使用sprintf比使用print更好。 I tried but it takes way more space. 我尝试过,但是占用更多空间。

For example : 例如 :

  char toWrite[18];
  sprintf(toWrite,"%d/%d/%d %d:%d:%d",RTC.now().day(),RTC.now().month(),RTC.now().year()-2000,RTC.now().hour(),RTC.now().minute(),RTC.now().second());
  tft.println(toWrite);

takes more space than : 占用的空间比:

  tft.print(RTC.now().day(), DEC);
  tft.print('/');
  tft.print(RTC.now().month(), DEC);
  tft.print('/');
  tft.print(RTC.now().year(), DEC);
  tft.print(' ');
  tft.print(RTC.now().hour(), DEC);
  tft.print(':');
  tft.print(RTC.now().minute(), DEC);
  tft.print(':');
  tft.println(RTC.now().second(), DEC);
  tft.println();

Could someboby explain me why ? 有人可以解释一下为什么吗?

Many thanks ! 非常感谢 !

PS : Sorry for my English, it's not my mother tongue =) PS:对不起,我的英语不是我的母语=)

The routine sprintf is larger because it is a more complicated (and more flexible) routine than print. 例程sprintf较大,因为它是比print更复杂(和更灵活)的例程。 You can make your code smaller by having more arduous print statements. 您可以通过使用更繁琐的打印语句来使代码更小。 Unfortunately, there is no free lunch in this case. 不幸的是,在这种情况下没有免费的午餐。

You can really cut down printf if you remove the extraneous formats. 如果删除多余的格式,则可以真正减少printf。
Here is an example alternate fprintf (printf is just fprintf with 1 as first arg) that compiles down to 1/2kb including my conversion functions (it could be smaller if you remove more) 这是一个示例性的fprintf(printf只是fprintf,第一个arg为1),包括我的转换函数,它可以编译为1 / 2kb(如果删除更多,则可能会更小)

void myfprintf_(int fd,int nargs, ...){ 
   va_list ap; va_start(ap, nargs); static char *s; const char *fmt; 
   fmt=va_arg(ap, char *); 
   int i=0,p; 
   char buf[80]; 
while (fmt[i]){ 
   p=0; 
   while (fmt[i]!='%' && fmt[i]!=0) buf[p++]=fmt[i++]; 
   if (p != 0) write(fd,buf,p); 
   if (nargs-->0){ 
      switch (fmt[++i]) { 
      case 's': s=va_arg(ap, char *); break; 
      case 'd': s=dtos(va_arg(ap, int)); break; 
      case 'x': s=dtox(va_arg(ap, int),'a'); break; 
      case 'X': s=dtox(va_arg(ap, int),'A' ); break; 
      case 'f': s=ftos(va_arg(ap, double)); break; 
      case 'c': buf[0]=(va_arg(ap, int));buf[1]=0;s=buf;break; 
      case '%': s="%"; break; 
      default : s="";break; 
      } write(fd,s,strlen(s)); 
   } 
i++; 
} 
va_end(ap); 
}

just comment out the formats you won't need and modify for your existing conversion functions - Also if you want it to be more compliant, make it an int function vs void and sum the returns of write for the return value ... though 99% of the time I don't use printf's return. 只是注释掉不需要的格式,并为现有的转换函数进行修改-同样,如果您希望它更加兼容,请将其设置为int vs vs void并求和返回值的写返回值...尽管99我不使用printf的回报的时间百分比。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM