0

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?

Codebeat
  • 6,501
  • 6
  • 57
  • 99

1 Answers1

1

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 );  
}
Community
  • 1
  • 1
Morgoth
  • 4,935
  • 8
  • 40
  • 66
  • Thanks. I thought the third parameter was the buffer size, that's why I was using 7 (because of buff[10]) instead of 10. Thanks allot, easy fix and saves me 4% of executable space (comparing when using sprintf instead of itoa). Just figure out you can also use utoa. – Codebeat Mar 17 '17 at 01:25