我很难用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()函数打印错误的数字?任何解决方案如何解决这个问题?
此行itoa( (uint8_t)getVolume() ,&buff[2],7 ); // get percent
是错误的。
您在基地10中要求它在基本7中的数字。
。这是一个快速计算:
99÷7 = 14 r 1
14÷7 = 2 r 0
∴99 10 = 201 7
完整代码
校正的示例如下所示:
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 );
}