【问题标题】:Arduino: itoa prints 201 and sprintf prints the intended 99Arduino:itoa 打印 201 和 sprintf 打印预期的 99
【发布时间】:2017-03-16 04:53:11
【问题描述】:

我在使用 itoa() 打印字节值 (uint8_t) 时遇到困难,需要打印一定百分比的体积。我想使用这个函数,因为它减少了二进制大小。

两个版本的 updateStats 函数(使用 OLED_I2C 库在 oled 显示器上打印统计信息:OLED display(SDA, SCL, 8); ):

ITOA(不工作,打印 V:201%)

void updateStats()
{
  char buff[10]; //the ASCII of the integer will be stored in this char array
  memset(buff, 0, sizeof(buff));

  buff[0] = 'V';
  buff[1] = ':';

  itoa( (uint8_t)getVolume() ,&buff[2],7 ); // get percent
  strcat( buff,"%" ); 

  display.print( getInputModeStr(), LEFT  , LINE3 );  
  display.print( buff, RIGHT , LINE3 );  
}

SPRINTF(按预期工作,打印 V:99%)

void updateStats()
{
  char buff[10]; //the ASCII of the integer will be stored in this char array
  memset(buff, 0, sizeof(buff));
  sprintf(buff, "V:%d%%", (uint8_t)getVolume() ); // get percent

  display.print( getInputModeStr(), LEFT  , LINE3 );  
  display.print( buff, RIGHT , LINE3 );  
}

问题

知道为什么 itoa() 函数会打印错误的数字吗?有什么办法解决这个问题吗?

【问题讨论】:

    标签: arduino byte percentage uint8t itoa


    【解决方案1】:

    itoa( (uint8_t)getVolume() ,&buff[2],7 ); // get percent 这一行是错误的。

    当您想要以 10 为底时,您要求以 7 为底的数字。

    这是一个快速计算:

    99 ÷ 7 = 14 r 1
    14 ÷ 7 = 2 r 0
    ∴ 9910 = 2017

    完整代码

    修正后的例子如下:

    void updateStats()
    {
      char buff[10]; //the ASCII of the integer will be stored in this char array
      memset(buff, 0, sizeof(buff));
    
      buff[0] = 'V';
      buff[1] = ':';
    
      itoa( (uint8_t)getVolume() ,&buff[2], 10 ); // get percent
      strcat( buff,"%" ); 
    
      display.print( getInputModeStr(), LEFT  , LINE3 );  
      display.print( buff, RIGHT , LINE3 );  
    }
    

    【讨论】:

    • 谢谢。我认为第三个参数是缓冲区大小,这就是为什么我使用 7(因为 buff[10])而不是 10。感谢分配,轻松修复并为我节省 4% 的可执行空间(比较使用 sprintf 而不是 itoa) .只要弄清楚你也可以使用 utoa。
    猜你喜欢
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2012-11-15
    相关资源
    最近更新 更多