Skip to content

Commit

Permalink
fix: print(0ULL) output nothing
Browse files Browse the repository at this point in the history
Fixes stm32duino#2545

Signed-off-by: warmonkey <luoshumymail@gmail.com>
  • Loading branch information
warmonkey authored and fpistm committed Nov 4, 2024
1 parent c35b8ef commit 3250030
Showing 1 changed file with 41 additions and 35 deletions.
76 changes: 41 additions & 35 deletions cores/arduino/Print.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down

0 comments on commit 3250030

Please sign in to comment.