2017-09-26 2:49 PM
Hello all!
I'm using stvd and Cosmic (free) C compiler and I'm having issues with a simple statement. I'm using sprintf to conver two uint8_t to string but it always do it wrong.
uint8_t u8Hours = 22, u8Minutes = 31;
uint8_t u8DisplayBuffer[6];
sprintf(u8DisplayBuffer, ''%.2u%.2u'', u8Hours, u8Minutes );
the result is an array with ''5663''
♯♯♯
I have tried everything on my mind but I can't figure it out what is happening, do you have some idea what can be wrong?
Thanks in advanced,
Best regards, Mauro.
#sprintf #stm8 #cosmicSolved! Go to Solution.
2017-09-26 4:31 PM
Try using an unsigned int
22 * 256 + 31 = 5663
unsigned int u8Hours = 22, u8Minutes = 31;
uint8_t u8DisplayBuffer[6];
sprintf(u8DisplayBuffer, '%.2u%.2u', u8Hours, u8Minutes );
or
uint8_t u8Hours = 22, u8Minutes = 31;
uint8_t u8DisplayBuffer[6];
sprintf(u8DisplayBuffer, '%.2u%.2u', (unsigned int)u8Hours, (unsigned int)u8Minutes );
2017-09-26 4:31 PM
Try using an unsigned int
22 * 256 + 31 = 5663
unsigned int u8Hours = 22, u8Minutes = 31;
uint8_t u8DisplayBuffer[6];
sprintf(u8DisplayBuffer, '%.2u%.2u', u8Hours, u8Minutes );
or
uint8_t u8Hours = 22, u8Minutes = 31;
uint8_t u8DisplayBuffer[6];
sprintf(u8DisplayBuffer, '%.2u%.2u', (unsigned int)u8Hours, (unsigned int)u8Minutes );
2017-09-26 6:37 PM
Hello Clive One, thank you very much for the quick answer,
I've tested with the type casts and it worked, thank you so much.
unfortunately I don't understand why, is there a short way to explain why it requires the conversion to 'unsigned int'?
Best regards, Mauro.
2017-09-26 7:08 PM
Because %u expects a 16-bit parameter, and apparently Cosmic folds 8-bit values.
The prototype for sprintf() doesn't infer any size on the parameters, thus no warning, or ability for the compiler to make better choices.
We’re moving the ST Community to a new platform to give you a better and more reliable community experience.