From 145ded01040afa00d74eb11c2e26c7223287084f Mon Sep 17 00:00:00 2001 From: Stuart Gorman <32289199+StuartGorman@users.noreply.github.com> Date: Fri, 20 Mar 2020 16:04:09 +1000 Subject: [PATCH] native 16bit int and large floats fix On a processor where an int is 16 bit, the max float value will be capped to 32767 due to type conversions. The PRINTF_MAX_FLOAT define is meant to prevent the limitation being exposed but it was written with 32 bit ints in mind. Explicitly setting the conversion type to int32_t fixes this. Added a note in readme against the define as a gotcha --- README.md | 2 +- printf.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2122653e..fd08d0a0 100644 --- a/README.md +++ b/README.md @@ -172,7 +172,7 @@ int length = sprintf(NULL, "Hello, world"); // length is set to 12 | PRINTF_NTOA_BUFFER_SIZE | 32 | ntoa (integer) conversion buffer size. This must be big enough to hold one converted numeric number _including_ leading zeros, normally 32 is a sufficient value. Created on the stack | | PRINTF_FTOA_BUFFER_SIZE | 32 | ftoa (float) conversion buffer size. This must be big enough to hold one converted float number _including_ leading zeros, normally 32 is a sufficient value. Created on the stack | | PRINTF_DEFAULT_FLOAT_PRECISION | 6 | Define the default floating point precision | -| PRINTF_MAX_FLOAT | 1e9 | Define the largest suitable value to be printed with %f, before using exponential representation | +| PRINTF_MAX_FLOAT | 1e9 | Define the largest suitable value to be printed with %f, before using exponential representation. Note that this should be set to be less than int32 max (2,147,483,647) to avoid issues | | PRINTF_DISABLE_SUPPORT_FLOAT | undefined | Define this to disable floating point (%f) support | | PRINTF_DISABLE_SUPPORT_EXPONENTIAL | undefined | Define this to disable exponential floating point (%e) support | | PRINTF_DISABLE_SUPPORT_LONG_LONG | undefined | Define this to disable long long (%ll) support | diff --git a/printf.c b/printf.c index 8a700add..41c9cd61 100644 --- a/printf.c +++ b/printf.c @@ -380,7 +380,7 @@ static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, d prec--; } - int whole = (int)value; + int32_t whole = (int32_t)value; double tmp = (value - whole) * pow10[prec]; unsigned long frac = (unsigned long)tmp; diff = tmp - frac;