Converting floats and integers to char*

左心房为你撑大大i 提交于 2019-12-12 07:05:08

问题


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?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/13090868/converting-floats-and-integers-to-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!