Go Down

Topic: int to char trouble (Read 981 times) previous topic - next topic

Nick Gammon


The itoa() function can convert an int to an array of characters, too, but without any control over the format of the resulting array of characters (similar to %d), at a fraction of the overhead of sprintf, if memory is a problem.


Indeed, a quick test shows that using sprintf takes 1368 more bytes of program than using itoa. So if you are down to your last 1500 bytes or so, and have no other reason to use sprintf, then itoa might save the day. Example:

Code: [Select]
int reading = myDHT22.getTemperatureC();
char buf [20];
itoa (reading, buf, 10);


With itoa you can specify a base too (eg. base 10 as in the example, or base 16 for hex).

In both cases you need to make sure the buffer is long enough to hold the converted number.

TomK

i am now using itoa and like you said i am saving about 1500 bytes. this is great because i plan to add a rtc which will also use the itoa conversion so i will need that saved space.
thanks

Nick Gammon

That's great! Between us we got things going and saved you some space.

I should point out though that you don't use the 1500 bytes every time you call sprintf. Only calling it once causes its code to be incorporated in your sketch. After that, subsequent uses are "free".

TomK

Ohhhhhh I see. So the first time I call sprintf, or some other function, it gets written to the memory, then each time I call it again it just refers back to that memory?
At least now I have more space for the rtc code and anything else I may incorporate.

Nick Gammon

Sort of. When you use a function the linker includes it as part of your program code. So the more things you use the larger the program gets (plus the stuff you write yourself).

Go Up