how to convert an integer to string?

13,303

Solution 1

sprintf will format a string

Quick example:

char buf[50];
uint8_t count = 10;
sprintf(buf,'%d',count);

lcd_puts(buf);

Solution 2

On a microcontroller, you have to be at least a little worried about performance (which rules out sprintf), even division is a very expensive operation on such chips. So you want code optimized for a microcontroller.

I've written some here: http://ideone.com/SsEUW (will need a few changes for use with C-style strings instead of C++, but the method should be clear)

Solution 3

It depends on what lcd_puts does with its argument. One possibility is as follows:

void send_to_lcd(uint8_t count)
{
    char str[SOME_CONSERVATIVE_MAX_LENGTH];
    sprintf(str, "%d", count);  // You might also snprintf() if it's available
    lcd_puts(str);
}

But remember that str goes out of scope as soon as send_to_lcd() returns. So if lcd_puts "remembers" its input argument, this will have undefined behaviour.

If that's the case, you will have to malloc a string buffer instead. But then you'll need to remember to free() it at some point, and it all gets rather messy.

Solution 4

This seems like a reasonable approach.

#include <stdint.h>
#include <stdio.h>

const char *u82s(uint8_t count)
{
    static char aString[4];

    aString[3] = '\0';
    aString[2] = (count % 10) + '0';  count /= 10;
    aString[1] = (count % 10) + '0';  count /= 10;
    aString[0] = (count % 10) + '0';

    return aString;
}

int main(void)
{
    uint8_t z = UINT8_MAX;

    do
    {
        z++;
        printf("%s\n", u8ts(z));
    }
    while (z != UINT8_MAX);

    return 0;
}
Share:
13,303
w_hoami
Author by

w_hoami

Updated on June 04, 2022

Comments

  • w_hoami
    w_hoami about 2 years

    I have a standard c function with the following prototype

    extern void lcd_puts(const char *s);
    

    in my other function i have something like this

    send_to_lcd() {
      uint8_t count = 10
      lcd_puts(count);
    }
    

    my question is how do i convert count to a string pointer to be able to send it to lcd_puts which should print out the count on a lcd screen

    thanks

  • Oliver Charlesworth
    Oliver Charlesworth almost 13 years
    You don't necessarily have to be worried. It depends if it's time-critical. Prefer standard-library routines over rolling your own until you know that you need to.
  • Ben Voigt
    Ben Voigt almost 13 years
    @Oli: itoa as suggested by Owen might be feasible, but sprintf is a horrible choice on a microcontroller.
  • Oliver Charlesworth
    Oliver Charlesworth almost 13 years
    Until the OP adds the words "I need it to be fast" to his/her question, I stick with my answer that sprintf is the best choice here; it's a widely-supported standard library function (one can't say the same for itoa).
  • Owen
    Owen almost 13 years
    @Oli Yes, probably sprint would be fine, if he's writing to an LCD screen it's not like you're gonna see the 1 ms (1000 cycles on 1MHz proc) or so delay. Be careful with it though because a lot of embedded libraries use a stripped-down, non-standard sprintf that might not do what you expect (like always print in Hex (PIC for %ld)), or none at all
  • Owen
    Owen almost 13 years
    Or, if you don't have malloc(), you could use a static buffer (but I don't think lcd_puts saves it's argument -- it's probably just setting digital pins).
  • Oliver Charlesworth
    Oliver Charlesworth almost 13 years
    @Owen: Yeah, probably not. I was just preparing for worst-case, where the LCD isn't actually updated til later or something.
  • EvilTeach
    EvilTeach almost 13 years
    As count is essentially a small unsigned integer, %s as a format to sprintf is likely to access violate.
  • EvilTeach
    EvilTeach almost 13 years
    He is looking for a C answer.
  • Owen
    Owen almost 13 years
    If this is on AVR you might want to use sprintf_P instead (nongnu.org/avr-libc/user-manual/…)
  • Jeff
    Jeff almost 13 years
    For microcontroller projects I avoid malloc.
  • Ben Voigt
    Ben Voigt almost 13 years
    @Owen: For many microcontrollers, even if performance isn't a concern, the kilobyte-or-more code size of sprintf is problematic. Many devices only have ~8kB code storage, some even less.
  • Ben Voigt
    Ben Voigt almost 13 years
    You wrote up a nice short (if very slow) version, then called printf anyway?
  • Ben Voigt
    Ben Voigt almost 13 years
    @EvilTeach: Most of the code can be used as-is, mostly just string retval(5, '\0'); needs to be replaced by static char retval[5] = { 0 };. In this unsigned case, it can be decreased to 4.
  • EvilTeach
    EvilTeach almost 13 years
    The printf occurs in the unit test, not the function. The question raised was for a method to turn a uint8_t into a char *. The function does that, without spending the overhead that would be associated with the printf family.
  • EvilTeach
    EvilTeach almost 13 years
    renamed function to indicate its intent.
  • w_hoami
    w_hoami almost 13 years
    I am just getting my hands wet at this uC thing, so performance for me is not a problem right now. I tried this and it worked out ofthe box. Thanks to everyone else for their comments and making me aware of performance issues.
  • Miro Samek
    Miro Samek almost 13 years
    The function u82s() as written is not reentrant, because it uses a static string. Perhaps a better design would be to provide the string as an argument. That way, the function could format the number in any place of a longer string. (But then it should not write '\0' at the end). I don't agree with the previous comment that this function is slow. In fact, it's perhaps an order of magnitude faster than snprintf() or similar functions. It is also orders of magnitude smaller in code size.
  • EvilTeach
    EvilTeach almost 13 years
    Reentrant was not a requirement. The question was how to turn an unsigned char into a cstring in an embedded environment. The interesting part is now to get those 3 characters onto the lcd screen. Nothing is said about what api is available for sending characters to the screen If it is a byte by byte, then integrating the code into the lcd function may be correct. If the embedded runtime has a printf already, that one might as well use that ;)
  • EvilTeach
    EvilTeach almost 13 years
    @ben i looked at the link and saw templates.
  • Ben Voigt
    Ben Voigt almost 13 years
    @EvilTeach: So? Lines 25-80 are perfectly good C code, which solves the problem. I assume that an embedded developer is capable of putting that into a function with a signature accepted by their compiler.
  • w_hoami
    w_hoami almost 13 years
    @EvilTeach: sorry about my inexpertise with c, but wondering when exactly does the u82s() function gets called?
  • EvilTeach
    EvilTeach almost 13 years
    I'll pop it in an answer so others can comment as well.
  • EvilTeach
    EvilTeach about 9 years
    renamed one name, but not in both places. Dah.
  • ChrisW
    ChrisW over 2 years
    This link doesn't work anymore, could you edit the answer with a working link or even quote the solution inline?
  • Ben Voigt
    Ben Voigt over 2 years
    @ChrisW: Sorry, I didn't keep a separate copy. Back then (over 10 years ago) I foolishly expected that ideone would abide by their own terms which said that posts were being kept forever (we're talking a couple kilobytes of data, the storage cost for 100 years is the tiniest fraction of a penny, so the promise was entirely believable)