I am working on developing an embedded system (Cortex M3). For sending some data from the device to the serial port (to show on a PC screen), I use some own functions using putchar() method.
When I want to send integer or float, I use sprintf() in order to convert them to string of characters and sending them to the serial port.
Now, them problem is that I am using Keil uVision IDE and it is limited version with max 32 KB. Whenever I call sprintf() in different functions, I don't know why the size of the code after compile increased too much. I have surpassed 32 KB now and I wonder I have to change some of my functions and use something else instead of sprintf!
Any clue?
Snprintf is safer to use because characters are not omitted and it is stored in the buffer for later usage. Both sprintf and snprintf store the string and produces the output as needed by user.
Unfortunately, a number of commonly used library functions, including strcpy , strcat , and sprintf , have the property that they can generate a byte sequence without being given any indication of the size of the destination buffer [97]. Such conditions can lead to vulnerabilities to buffer overflow.
12, printf() takes 42682 cycles and sprintf() takes 38955 cycles. This is with -msmart-io=2 enabled. The speed difference is likely due to the time waiting for the I/O.
The sprintf() function writes a formatted string to a variable. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step".
Two potential offerings (neither of which I have used myself - my compiler vendors usually supply a stripped down printf
for embedded use):
http://eprintf.sourceforge.net/ - [Sep 2017: unfortunately, seems to have gone away, but source code still here: https://sourceforge.net/projects/eprintf/files/ ]
http://www.sparetimelabs.com/tinyprintf/index.html - 2 files, about 1.4KB code. Option to enable 'longs' (means more code size). Supports leading zeros and field widths. No floating point support.
If you want it to be efficient, the best way is probably to code it yourself, or find some already written code for it on the net. Int to string conversion is however very simple, every programmer can write that in less than 30 minutes. Float to string conversion is a bit more intricate and depends on the floating point format used.
For convenience, here is a simple int-to-string algorithm for use in microcontroller applications:
void get_dec_str (uint8_t* str, size_t len, uint32_t val)
{
uint8_t i;
for(i=1; i<=len; i++)
{
str[len-i] = (uint8_t) ((val % 10UL) + '0');
val/=10;
}
str[i-1] = '\0';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With