简体   繁体   中英

Converting floats and integers to char*

I'm new to C and was kind of thrust into this world of embedded processing with C. I need to convert to char* and output integers and floating point numbers (only 0.01 resolution) to an LCD screen with an 8 bit interface. I've been reading through some of the posts and I see all these great ideas for converting int and float to char* but I'm not exactly sure what's going on in them.

Can someone provide a method for my two queries and a little explanation?

It actually depends upon the standard library, and in some embedded systems that library is partially implemented, or even absent. With a fully standard C99 implementation you might do something like

char buf[40];
int i;
double x;
// compute i & x, then make a string from them with::
snprintf(buf, sizeof(buf), "i=%2d x=%.2f", i, x);

Then you might send that buf to your LCD port, or strdup it for later usage. (If you use strdup you'll need to free the result).

Read the documentation of snprintf for details. You probably should test the return int value of snprintf .

Since you're working on embedded programming you skould be aware of the fact that standard conversions often make use of divisions which are very taxing on any processor.

Since integers are converted using divide-by-ten you could instead implement a division using multiplication by invariant integers. This method should allow you to convert most values in the time it takes to convert a single digit in a value using division.

For floating point use the following steps:

  1. save the sign and take the absolute value if sign is negative
  2. multiply by 10.0 raised to the number of decimals you need
  3. add 0.5 and convert to an integer
  4. convert the integer to a string using the division method previously suggested
  5. make sure the string is at least number of decimals + 1, insert ascii 0 at beginning as necessary
  6. insert a minus sign at the beginning as required
  7. insert a decimal point at the appropriate position

Here is an example that requires two decimals

3758.3125
375831.25    (multiply by 10^2)
375831.75    (add 0.5)
375831       (convert to integer)
"375831"     (convert to string)
"3758.31"    (insert decimal point => final result)

A somewhat more difficult case

-0.0625
0.0625       (keep sign)
6.25         (multiply by 10^2)
6.75         (add 0.5)
6            (convert to integer)
"6"          (convert to string)
"006         (insert ascii 0 as required)
"-006"       (insert minus sign)
"-0.06"      (insert decimal point => final result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM