Skip to content

Commit 2ca94a4

Browse files
sandeepmistryfacchinm
authored andcommitted
Use two ltoa calls with trimming instead of sprintf on AVR
1 parent 964b662 commit 2ca94a4

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
@@ -566,6 +566,38 @@ static cJSON_bool print_number(const cJSON * const item, printbuffer * const out
566566
}
567567
else
568568
{
569+
#ifdef __AVR__
570+
(void)test;
571+
572+
// zero the buffer
573+
memset(number_buffer, 0x00, sizeof(number_buffer));
574+
575+
// add the integer part
576+
ltoa((long)d, (char*)number_buffer, 10);
577+
length = strlen((char*)number_buffer);
578+
579+
// calculate the number of decimal points (up to 9)
580+
long decimal = (long)((d - (long)d) * 1000000000L);
581+
582+
if (decimal < 0) {
583+
// negative decimal, make it positive
584+
decimal *= -1;
585+
}
586+
587+
// trim the trailing zeros
588+
while (decimal && (decimal % 10) == 0) {
589+
decimal /= 10;
590+
}
591+
592+
if (decimal) {
593+
// add the decimal part
594+
number_buffer[length] = decimal_point;
595+
596+
ltoa(decimal, (char*)&number_buffer[length + 1], 10);
597+
598+
length = strlen((char*)number_buffer);
599+
}
600+
#else
569601
/* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
570602
length = sprintf((char*)number_buffer, "%1.15g", d);
571603

@@ -575,6 +607,7 @@ static cJSON_bool print_number(const cJSON * const item, printbuffer * const out
575607
/* If not, print with 17 decimal places of precision */
576608
length = sprintf((char*)number_buffer, "%1.17g", d);
577609
}
610+
#endif
578611
}
579612

580613
/* sprintf failed or buffer overrun occurred */

0 commit comments

Comments
 (0)