aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid A. Mellis <d.mellis@arduino.cc>2011-05-07 18:17:32 -0400
committerDavid A. Mellis <d.mellis@arduino.cc>2011-05-07 18:17:32 -0400
commit5e5cce81240b39c6068380cd786ac59c2ce88c07 (patch)
tree237e8b02cb15f6f7514fb27a5955d444639ed710
parentac5defcea611319084ca7334b347c061a95e00ac (diff)
Optimizing printing of numbers (writing a single buffer).
Fix from Bill Greiman via Limor.
-rwxr-xr-xcores/arduino/Print.cpp28
1 files changed, 13 insertions, 15 deletions
diff --git a/cores/arduino/Print.cpp b/cores/arduino/Print.cpp
index eac145f..0a580b7 100755
--- a/cores/arduino/Print.cpp
+++ b/cores/arduino/Print.cpp
@@ -179,25 +179,23 @@ void Print::println(double n, int digits)
// Private Methods /////////////////////////////////////////////////////////////
-void Print::printNumber(unsigned long n, uint8_t base)
-{
- unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars.
- unsigned long i = 0;
+void Print::printNumber(unsigned long n, uint8_t base) {
+ char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
+ char *str = &buf[sizeof(buf) - 1];
- if (n == 0) {
- print('0');
- return;
- }
+ *str = '\0';
+
+ // prevent crash if called with base == 1
+ if (base < 2) base = 10;
- while (n > 0) {
- buf[i++] = n % base;
+ do {
+ unsigned long m = n;
n /= base;
- }
+ char c = m - base * n;
+ *--str = c < 10 ? c + '0' : c + 'A' - 10;
+ } while(n);
- for (; i > 0; i--)
- print((char) (buf[i - 1] < 10 ?
- '0' + buf[i - 1] :
- 'A' + buf[i - 1] - 10));
+ write(str);
}
void Print::printFloat(double number, uint8_t digits)