Keith Packard: picolibc-string-float
Float/String Conversion in Picolibc
Exact conversion between strings and floats seems like a fairly
straightforward problem. There are two related problems:
- String to Float conversion. In this case, the goal is to construct the floating point number which most closely approximates the number represented by the string.
- Float to String conversion. Here, the goal is to generate the shortest string which, when fed back into the String to Float conversion code, exactly reproduces the original value.
abort
. Again, on platforms with an OS, that at least provides a
way to shut down the program and let the operating environment figure
out what to do next. On tiny embedded systems, there may not be any
way to log an error message or even restart the system.
Ok, so we want to get rid of the calls to abort and have the error
reported back through the API call which caused the problem. That's
got two issues, one mere technical work, and another mere
re-interpretation of specifications.
Let's review the specification issue. The libc APIs involved here are:
Input:
- scanf
- strtod
- atof
- printf
- ecvt, fcvt
- gcvt
- strtod. About the best we can do is report that no conversion was performed.
- atof. Atof explicitly fails to detect any errors, so all we can do is return zero. Maybe returning NaN would be better?
- ecvt, fcvt and gcvt. These return a pointer, so they can return NULL on failure.
- No stores through NULL pointers
- Report failure to the application
- No memory leaks