diff options
author | David A. Mellis <d.mellis@arduino.cc> | 2011-05-07 18:17:32 -0400 |
---|---|---|
committer | David A. Mellis <d.mellis@arduino.cc> | 2011-05-07 18:17:32 -0400 |
commit | 5e5cce81240b39c6068380cd786ac59c2ce88c07 (patch) | |
tree | 237e8b02cb15f6f7514fb27a5955d444639ed710 /cores | |
parent | ac5defcea611319084ca7334b347c061a95e00ac (diff) |
Optimizing printing of numbers (writing a single buffer).
Fix from Bill Greiman via Limor.
Diffstat (limited to 'cores')
-rwxr-xr-x | cores/arduino/Print.cpp | 28 |
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) |