Arduino: itoa prints 201 and sprintf prints the intended 99

1.3k Views Asked by At

I have difficulties printing a byte value (uint8_t) with itoa(), needed to print a percentage of volume. I want to use this function because it reduce binary size.

Two versions of an updateStats function (prints stats on a oled display using OLED_I2C library: OLED display(SDA, SCL, 8); ):

ITOA (NOT WORKING, PRINTS 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 (WORKS AS EXPECTED, PRINTS 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 );  
}

Question

Any idea why the itoa() function prints a wrong number? Any solution how to solve this?

1

There are 1 best solutions below

1
Morgoth On BEST ANSWER

This line itoa( (uint8_t)getVolume() ,&buff[2],7 ); // get percent is wrong.

You asking for the number in base 7, when you want it in base 10.

Here's a quick calculation:

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

Full Code

The corrected example is shown below:

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 );  
}