How can I convert a float
value to char*
in C
language?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
You can access to float data value byte by byte and send it through 8-bit output buffer (e.g. USART) without casting.
Long after accept answer.
Use
sprintf()
, or related functions, as many others have answers suggested, but use a better format specifier.Using
"%.*e"
, code solves various issues:The maximum buffer size needed is far more reasonable, like 18.
sprintf(buf, "%f", FLT_MAX);
could need 47+.sprintf(buf, "%f", DBL_MAX);
may need 317+Using
".*"
allows code to define the number of decimal places needed to distinguish a string version offloat x
and it next highestfloat
. For deatils, see Printf width specifier to maintain precision of floating-point valueUsing
"%e"
allows code to distinguish smallfloat
s from each other rather than all printing"0.000000"
which is the result when|x| < 0.0000005
.Ideas:
IMO, better to use 2x buffer size for scratch pads like
buf[FLT_STRING_SIZE*2]
.For added robustness, use
snprintf()
.That will store the string representation of
myFloat
inmyCharPointer
. Make sure that the string is large enough to hold it, though.snprintf
is a better option thansprintf
as it guarantees it will never write past the size of the buffer you supply in argument 2.sprintf: (from MSDN)
In Arduino: