Skip to content

Commit 1747292

Browse files
committed
Optimizing printing of numbers (writing a single buffer).
Fix from Bill Greiman via Limor.
1 parent cf044cd commit 1747292

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

hardware/arduino/cores/arduino/Print.cpp

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -179,25 +179,23 @@ void Print::println(double n, int digits)
179179

180180
// Private Methods /////////////////////////////////////////////////////////////
181181

182-
void Print::printNumber(unsigned long n, uint8_t base)
183-
{
184-
unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars.
185-
unsigned long i = 0;
182+
void Print::printNumber(unsigned long n, uint8_t base) {
183+
char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
184+
char *str = &buf[sizeof(buf) - 1];
186185

187-
if (n == 0) {
188-
print('0');
189-
return;
190-
}
186+
*str = '\0';
187+
188+
// prevent crash if called with base == 1
189+
if (base < 2) base = 10;
191190

192-
while (n > 0) {
193-
buf[i++] = n % base;
191+
do {
192+
unsigned long m = n;
194193
n /= base;
195-
}
194+
char c = m - base * n;
195+
*--str = c < 10 ? c + '0' : c + 'A' - 10;
196+
} while(n);
196197

197-
for (; i > 0; i--)
198-
print((char) (buf[i - 1] < 10 ?
199-
'0' + buf[i - 1] :
200-
'A' + buf[i - 1] - 10));
198+
write(str);
201199
}
202200

203201
void Print::printFloat(double number, uint8_t digits)

0 commit comments

Comments
 (0)