cancel
Showing results for 
Search instead for 
Did you mean: 

Cosmic STM8 sprintf

maurosmartins
Associate II
Posted on September 26, 2017 at 23:49

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'' 

0690X00000608K9QAI.png♯♯♯

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 #cosmic
1 ACCEPTED SOLUTION

Accepted Solutions
Posted on September 27, 2017 at 01:31

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

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

View solution in original post

3 REPLIES 3
Posted on September 27, 2017 at 01:31

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

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Posted on September 27, 2017 at 01:37

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.

Posted on September 27, 2017 at 02:08

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.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..