Skip to main content
Visitor II
September 26, 2017
Solved

Cosmic STM8 sprintf

  • September 26, 2017
  • 1 reply
  • 2309 views
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
    This topic has been closed for replies.
    Best answer by Tesla DeLorean
    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 );

    1 reply

    Graduate II
    September 26, 2017
    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 );

    September 27, 2017
    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.

    Graduate II
    September 27, 2017
    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.