diff --git a/cores/arduino/Print.cpp b/cores/arduino/Print.cpp index e9267405a5..62623492df 100644 --- a/cores/arduino/Print.cpp +++ b/cores/arduino/Print.cpp @@ -374,46 +374,52 @@ size_t Print::printULLNumber(unsigned long long n64, uint8_t base) char buf[64]; uint8_t i = 0; uint8_t innerLoops = 0; + size_t bytes = 0; - // prevent crash if called with base == 1 - if (base < 2) { - base = 10; - } - - // process chunks that fit in "16 bit math". - uint16_t top = 0xFFFF / base; - uint16_t th16 = 1; - while (th16 < top) { - th16 *= base; - innerLoops++; - } + // Special case workaround https://github.com/arduino/ArduinoCore-API/issues/178 + if (n64 == 0) { + write('0'); + bytes = 1; + } else { + // prevent crash if called with base == 1 + if (base < 2) { + base = 10; + } - while (n64 > th16) { - // 64 bit math part - uint64_t q = n64 / th16; - uint16_t r = n64 - q * th16; - n64 = q; - - // 16 bit math loop to do remainder. (note buffer is filled reverse) - for (uint8_t j = 0; j < innerLoops; j++) { - uint16_t qq = r / base; - buf[i++] = r - qq * base; - r = qq; + // process chunks that fit in "16 bit math". + uint16_t top = 0xFFFF / base; + uint16_t th16 = 1; + while (th16 < top) { + th16 *= base; + innerLoops++; } - } - uint16_t n16 = n64; - while (n16 > 0) { - uint16_t qq = n16 / base; - buf[i++] = n16 - qq * base; - n16 = qq; - } + while (n64 > th16) { + // 64 bit math part + uint64_t q = n64 / th16; + uint16_t r = n64 - q * th16; + n64 = q; + + // 16 bit math loop to do remainder. (note buffer is filled reverse) + for (uint8_t j = 0; j < innerLoops; j++) { + uint16_t qq = r / base; + buf[i++] = r - qq * base; + r = qq; + } + } - size_t bytes = i; - for (; i > 0; i--) { - write((char)(buf[i - 1] < 10 ? - '0' + buf[i - 1] : - 'A' + buf[i - 1] - 10)); + uint16_t n16 = n64; + while (n16 > 0) { + uint16_t qq = n16 / base; + buf[i++] = n16 - qq * base; + n16 = qq; + } + bytes = i; + for (; i > 0; i--) { + write((char)(buf[i - 1] < 10 ? + '0' + buf[i - 1] : + 'A' + buf[i - 1] - 10)); + } } return bytes; }