This is a speed-optimized solution for converting int (16-bit integer) to string.
This implementation avoids the use of division, since the 8-bit AVR used for Arduino does not have a hardware DIV command, the compiler translates division into lengthy repeated subtractions. Thus, the fastest solution uses conditional branches to build the string.
Fixed buffer with 7 bytes received from the beginning in RAM to avoid dynamic allocation. Since this is only 7 bytes, the cost of using fixed memory is considered minimal. To help the compiler, we add a case modifier to the variable declaration to speed up execution.
char _int2str[7]; char* int2str( register int i ) { register unsigned char L = 1; register char c; register boolean m = false; register char b; // lower-byte of i // negative if ( i < 0 ) { _int2str[ 0 ] = '-'; i = -i; } else L = 0; // ten-thousands if( i > 9999 ) { c = i < 20000 ? 1 : i < 30000 ? 2 : 3; _int2str[ L++ ] = c + 48; i -= c * 10000; m = true; } // thousands if( i > 999 ) { c = i < 5000 ? ( i < 3000 ? ( i < 2000 ? 1 : 2 ) : i < 4000 ? 3 : 4 ) : i < 8000 ? ( i < 6000 ? 5 : i < 7000 ? 6 : 7 ) : i < 9000 ? 8 : 9; _int2str[ L++ ] = c + 48; i -= c * 1000; m = true; } else if( m ) _int2str[ L++ ] = '0'; // hundreds if( i > 99 ) { c = i < 500 ? ( i < 300 ? ( i < 200 ? 1 : 2 ) : i < 400 ? 3 : 4 ) : i < 800 ? ( i < 600 ? 5 : i < 700 ? 6 : 7 ) : i < 900 ? 8 : 9; _int2str[ L++ ] = c + 48; i -= c * 100; m = true; } else if( m ) _int2str[ L++ ] = '0'; // decades (check on lower byte to optimize code) b = char( i ); if( b > 9 ) { c = b < 50 ? ( b < 30 ? ( b < 20 ? 1 : 2 ) : b < 40 ? 3 : 4 ) : b < 80 ? ( i < 60 ? 5 : i < 70 ? 6 : 7 ) : i < 90 ? 8 : 9; _int2str[ L++ ] = c + 48; b -= c * 10; m = true; } else if( m ) _int2str[ L++ ] = '0'; // last digit _int2str[ L++ ] = b + 48; // null terminator _int2str[ L ] = 0; return _int2str; } // Usage example: int i = -12345; char* s; void setup() { s = int2str( i ); } void loop() {}
This sketch was compiled into 1,082 bytes of code using avr-gcc, which is bundled with Arduino v1.0.5 (the size of the int2str function itself is 594 bytes). Compared to a solution using a String object that is compiled into 2.398 bytes, this implementation can reduce your code size by 1.2 Kb (it is assumed that you do not need another method of the String object, and your number strictly corresponds to the type of the signed type).
This function can be optimized further by writing it with the appropriate assembler code.
vcc2gnd Dec 13 '13 at 13:30 2013-12-13 13:30
source share