Skip to content

Commit 26e69ba

Browse files
committed
Use two ltoa calls with trimming instead of sprintf on AVR
1 parent e779d01 commit 26e69ba

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/cjson/cJSON.c

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,38 @@ static cJSON_bool print_number(const cJSON * const item, printbuffer * const out
493493
}
494494
else
495495
{
496+
#ifdef __AVR__
497+
(void)test;
498+
499+
// zero the buffer
500+
memset(number_buffer, 0x00, sizeof(number_buffer));
501+
502+
// add the integer part
503+
ltoa((long)d, (char*)number_buffer, 10);
504+
length = strlen((char*)number_buffer);
505+
506+
// calculate the number of decimal points (up to 9)
507+
long decimal = (long)((d - (long)d) * 1000000000L);
508+
509+
if (decimal < 0) {
510+
// negative decimal, make it positive
511+
decimal *= -1;
512+
}
513+
514+
// trim the trailing zeros
515+
while (decimal && (decimal % 10) == 0) {
516+
decimal /= 10;
517+
}
518+
519+
if (decimal) {
520+
// add the decimal part
521+
number_buffer[length] = decimal_point;
522+
523+
ltoa(decimal, (char*)&number_buffer[length + 1], 10);
524+
525+
length = strlen((char*)number_buffer);
526+
}
527+
#else
496528
/* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
497529
length = sprintf((char*)number_buffer, "%1.15g", d);
498530

@@ -502,6 +534,7 @@ static cJSON_bool print_number(const cJSON * const item, printbuffer * const out
502534
/* If not, print with 17 decimal places of precision */
503535
length = sprintf((char*)number_buffer, "%1.17g", d);
504536
}
537+
#endif
505538
}
506539

507540
/* sprintf failed or buffer overrun occured */

0 commit comments

Comments
 (0)