Skip to content

Commit 0133403

Browse files
committed
use less stack on number print
1 parent 0428ad8 commit 0133403

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

Diff for: cores/arduino/Print.cpp

+22-9
Original file line numberDiff line numberDiff line change
@@ -202,22 +202,35 @@ size_t Print::println(const Printable& x)
202202

203203
size_t Print::printNumber(unsigned long n, uint8_t base)
204204
{
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+
}
209209

210210
// prevent crash if called with base == 1
211211
if (base < 2) base = 10;
212212

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;
215220
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;
216228

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);
219232

220-
return write(str);
233+
return n;
221234
}
222235

223236
size_t Print::printFloat(double number, uint8_t digits)

0 commit comments

Comments
 (0)