File tree 1 file changed +22
-9
lines changed
1 file changed +22
-9
lines changed Original file line number Diff line number Diff line change @@ -202,22 +202,35 @@ size_t Print::println(const Printable& x)
202
202
203
203
size_t Print::printNumber (unsigned long n, uint8_t base)
204
204
{
205
- char buf[ 8 * sizeof ( long ) + 1 ]; // Assumes 8-bit chars plus zero byte.
206
- char *str = &buf[ sizeof (buf) - 1 ];
207
-
208
- *str = ' \0 ' ;
205
+ // shortcut printing just 0 prevents later overhead
206
+ if (n == 0 ) {
207
+ return write ( ' 0 ' );
208
+ }
209
209
210
210
// prevent crash if called with base == 1
211
211
if (base < 2 ) base = 10 ;
212
212
213
- do {
214
- char c = n % base;
213
+ unsigned long reverse = 0 ;
214
+ uint8_t digits = 0 ;
215
+
216
+ // reverse the number and count digits
217
+ while (n != 0 ) {
218
+ uint8_t remainder = n % base;
219
+ reverse = reverse * base + remainder ;
215
220
n /= base;
221
+ digits++;
222
+ }
223
+
224
+ // from here onwards reuse of variable 'n' to count written chars
225
+ do {
226
+ char c = reverse % base;
227
+ reverse /= base;
216
228
217
- *--str = c < 10 ? c + ' 0' : c + ' A' - 10 ;
218
- } while (n);
229
+ c = (c < 10 ? c + ' 0' : c + ' A' - 10 );
230
+ n += write (c);
231
+ } while (--digits);
219
232
220
- return write (str) ;
233
+ return n ;
221
234
}
222
235
223
236
size_t Print::printFloat (double number, uint8_t digits)
You can’t perform that action at this time.
0 commit comments