GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 16-Apr-2007, 06:17
crazypal crazypal is offline
New Member
 
Join Date: Apr 2007
Posts: 4
crazypal is on a distinguished road
Thumbs down

floating point decimal to ascii conversion


hi all i need the c code or the procedure for converting the floating point number into ascii so that i can display in the hyperterminal or send it to the LCD.

for eg:

float num;
num = 0.01123
i need this variable num is to be converted into ascii so that i can print the output with out using printf statement.

thanks in advance

aditya
  #2  
Old 16-Apr-2007, 08:04
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,720
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: floating point decimal to ascii conversion


Quote:
Originally Posted by crazypal
hi all i need the c code

Before writing a program to perform this task, you simply must give a better statement of requirements:

1. What function will you use to get the data to the LCD? That is: You put ascii chars for '0' - '9' and '.' into an array, then you put the chars out one at a time or what?

2. What kind of compiler are you using. If it has floating point numbers and floating point arithmetic, maybe it has sprintf? Or is it your feeling that sprintf would be "too expensive" in terms of code size and/or execution time? Are there any floating point conversion functions supplied with the compiler? (Sometimes compilers for embedded systems have floating-to-ascii conversion functions that are smaller and faster ---but less flexible--- than sprintf for a particular machine architecture.)

3. What is the desired format of the output? Fixed with five decimal place or
what?

4. What is the range of values that you want to put out? Between 0 and 1? Between -1 and 1? Between 0 and 10 to the power 37? What?

5. What would you require the program to do if a number is out of the range that you want to display?

6. What is the desired format of the output? Fixed with five decimal place or
what? Are there any requirements for alternative display formats (scientific-exponential for numbers larger or smaller than a certain value)?


Regards,

Dave
  #3  
Old 16-Apr-2007, 22:36
crazypal crazypal is offline
New Member
 
Join Date: Apr 2007
Posts: 4
crazypal is on a distinguished road
Thumbs down

Re: floating point decimal to ascii conversion


hi dave thanks for the reply......i am replyin to the queries u have asked.

1. What function will you use to get the data to the LCD? That is: You put ascii chars for '0' - '9' and '.' into an array, then you put the chars out one at a time or what?

i want to convert that floating point no to ascii and then i ll send each character to the LCD to display the number.

2. What kind of compiler are you using. If it has floating point numbers and floating point arithmetic, maybe it has sprintf? Or is it your feeling that sprintf would be "too expensive" in terms of code size and/or execution time? Are there any floating point conversion functions supplied with the compiler? (Sometimes compilers for embedded systems have floating-to-ascii conversion functions that are smaller and faster ---but less flexible--- than sprintf for a particular machine architecture.)

i am using high performance embedded workshop compiler which is used for 32 bit renesas controller. as i am using the trial version it is compatible upto 64k and i tried sprintf function in this i thk its not compatible with this compiler i m in d search of it whether is thr or not. there are no functions supplied with the compiler.

3. What is the desired format of the output? Fixed with five decimal place or
what?

the desired format is fixed with 3 decimal places.

4. What is the range of values that you want to put out? Between 0 and 1? Between -1 and 1? Between 0 and 10 to the power 37? What?

the range of values will be around 0 to 2.5.

5. What would you require the program to do if a number is out of the range that you want to display?

if it is out of range then it will display some garbage value.

6. What is the desired format of the output? Fixed with five decimal place or
what? Are there any requirements for alternative display formats (scientific-exponential for numbers larger or smaller than a certain value)?

the format is 3 numbers after the decimal. no there is no alternative for display format.


thanks in advance
aditya

Regards,

Dave[/quote]
  #4  
Old 17-Apr-2007, 04:04
crazypal crazypal is offline
New Member
 
Join Date: Apr 2007
Posts: 4
crazypal is on a distinguished road

Re: floating point decimal to ascii conversion


hi dave
i got the output using sprintf function so is thr any other method whr i can convert the floatin p‌oint no to ascii value.


aditya
  #5  
Old 17-Apr-2007, 08:31
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,720
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: floating point decimal to ascii conversion


Quote:
Originally Posted by crazypal
hi dave
i got the output using sprintf function so is thr any other method whr i can convert the floatin p‌oint no to ascii value.


aditya

The purpose of my questions was not for you to tell me what you want the program to do, but was to indicate to you what should be clearly stated (and understood) before starting to write the code.

Here's what I had in mind: A program specification.

If you don't have a program specification, how the heck can you test it? That is to say, how do you know that it does what it is supposed to do if you haven't clearly stated what it is supposed to do? And, more importantly: How can you know when you are through?

Here's an informal, but adequate, (I think) specification that incorporates your indicated requirements for a function to do the deed.

Input:
The input will be a float variable whose value is greater than or equal to 0 and less than or equal to 3.

Output:
The output will be stored in an array of chars whose contents can be used to create a display of the form
n.fff
Where n is the char that represents the integer part of the input value and the three chars fff represent the three most significant decimal digits of the fractional part.

Processing: Will be implemented in a function whose input parameter is a float, and a pointer to an array of chars that is large enough to hold the five chars of the output. Error detection is not required, and results obtained when values of the input variable that not are within the specified range can be anything at all. Under no circumstances is an invalid input allowed to make the program "misbehave". That is, output values are undefined, but the program sequence must be unaffected. As a specific example: the program can't go into an infinite loop or crash in some other manner if the calling program feeds it a negative value.

Method:

Function prototype:
CPP / C++ / C Code:
void float_to_fixed3(float x, char *display);
.
The variable display points to an array or other block of memory that can hold five chars.


The function itself could be implemented along these lines:

Code:
1. Declare an int variable, intpart. 2. (Optional) If rounding is required, then add 0.0005 to the value of x:
CPP / C++ / C Code:
    x += 0.0005;
3. Set intpart equal to the integer part of x:
CPP / C++ / C Code:
    intpart = x;
4. Store the char representation of intpart and store the decimal point:
CPP / C++ / C Code:
    display[0] = intpart + '0';
    display[1] = '.';
5. Subtract the integer part from x, leaving the fractional part:
CPP / C++ / C Code:
    x -= intpart;
6. Make a loop that does the following steps three times. (The loop index, i, goes from 2 up to and including 5):
CPP / C++ / C Code:
/* begin loop */
    /*
     * multiply x by 10.0, so that the integer part of the new 
     * value of x is equal to the value of next significant digit
     * of the fractional part
     */
     /* store the char representation of the value of the integer
      * part of the new value of x into display[i]
      */
     /* subtract the integer value of x from x, leaving the 
      * fractional part 
      */
/* end loop */
Here is a test program. Exercise (and debug) your function with this program compiled on your workstation. Then put the function into your embedded application.

CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>

char *float_to_fixed3(float f, char *buf);

int main()
{
    float f;
    int i;
    const int num_decimal_places = 3;
    /* The array must be at least two chars larger than the
     * number of decimal places
     */
    char buf[5]; 

    f = 0.0;
    while ((f >= 0.0) && (f < 10.0)) {
        printf("Enter a floating point number between 0 and 3: ");
        if ((scanf("%f", &f) != 1) || (f < 0) || (f > 3.0)) {
            f = -1.0;
        }
        else {
            float_to_fixed3(f, buf);
            printf("Here is the array: <");
            for (i = 0; i < num_decimal_places+2; i++) {
                printf("%c", buf[i]);
            }
            printf(">\n\n");
        }
    }
    return 0;
}

Output for a couple of numbers:

Code:
Enter a floating point number between 0 and 3: 1.23 Here is the array: <1.230> Enter a floating point number between 0 and 3: 1.415962 Here is the array: <1.416> Enter a floating point number between 0 and 3: -1

Note that I implemented rounding.

Note that my test program doesn't test for all possible "bad" inputs, but I think the function itself meets the program specification. That is, all steps of the function are executed a finite number of times, regardless of the program input. The function has no way of knowing whether the input array name is large enough, so there is absolutely nothing that the function itself can do to protect itself against a calling function that does not do it right. That's the nature of C.

For further consideration:
1. Is it desirable (or possible) to somehow change the function to make it absolutely bullet-proof against bad parameters? How the heck could that be done? (That is: protection against a programmer who calls this with a buffer that is less than 5 chars long? Can you protect against a programmer who calls this function with a pointer value that is totally invalid?)

2. You can (and maybe should) test for additional bad values if you want to. In other words change the test program to allow the user to give it numbers outside the required range. What happens if the function is fed a negative number? What about something like 9.99e13 or 9.99e-13? Stuff like that. Notice that making sure that the program doesn't do something "bad" in case of bad user input is at least as important in the so-called "real" world as making sure that it does the right thing with good input. See footnote.

3. Would there be any value added to the function if you made it return a pointer to char? You could make it test for out of range values and return NULL if input value is invalid. (And just return buf for successful conversion.) The calling program could use the return value to report errors.

4. How about making the function operate on an array of length 6 instead of 5 and putting a '\0' in the last element? Then you could use string functions on the result. For example, you could use strcpy() to copy the result to some other array. You could use something like fputs() or some other simple string output function to write to the output display. Stuff like that.

5. Note that, because a number involving decimal fractions may or may not (it depends on the number) be represented exactly as a binary floating point number in a computer, the result might be off by a digit in the least significant digit. Perhaps this should be added to the specification. For example, even with rounding, 1.9945 may come out as 1.994 or it may come out as 1.995. (It will be the same every time with a given compiler on a given architecture, but might be different for others.) Or you may find that 0.0035 and 0.0045 both display 0.004. If this is important, then you simply can't rely on floating point arithmetic anywhere in the calculations. (That is you must use fixed point representation, and, since there are no fixed point non-integer data types or operators in C, you will have to write your own routines.)

6. I have given a low-level way of extracting decimal digits from the fractional part. There are other ways.

For example: if you have a way to extract decimal digits from an integer, then you can first get the decimal digit(s) from the integer part of the input value. Then, (after subtracting the integer part), you can multiply the fractional part by 1000 and extract the three decimal digits from the integer part of the product (with optional rounding).

This may or may not be more efficient. It would involve one floating point multiplication by 1000 instead of the method that I presented, which involves three floating point multiplications by 10. Some compilers create incredibly efficient code for certain operations. Chances are that the conversion from float to int (that both methods would require) might overshadow other things anyhow, unless your platform has floating point hardware that takes care of such things. "Implement first; optimize later, if needed and/or appropriate." That's my motto.

Regards,

Dave

Footnote: I find it amusing that people seem to think that Murphy's law has something to do with "luck". That is, if you are unlucky, then something "will go wrong".

Actually the implication of Murphy's law for programmers is quite different:

If there is any way that bad user input (or other external factors) can cause unacceptable behavior, then you had for damn sure better change something, since there is one thing in this life that you should count on: Somehow, sometime (and, more than likely, at a very inopportune moment) your program will be given bad input.

Note that I used more words describing bad input than the actual functionality. (I could have used fewer words, I guess, but the point remains: make sure you know what the program must do and what it must not do.)
Last edited by davekw7x : 17-Apr-2007 at 09:57.
  #6  
Old 18-Apr-2007, 04:59
crazypal crazypal is offline
New Member
 
Join Date: Apr 2007
Posts: 4
crazypal is on a distinguished road

Re: floating point decimal to ascii conversion


thanks for ur help dave......

aditya
 
 

Recent GIDBlogWriting a book by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Convert Characters into Decimal value of ASCII ravi119 C Programming Language 3 15-Feb-2007 16:07
Decimal places. Weird... feicobain C Programming Language 1 07-Feb-2007 13:19
Binary to Decimal Conversion Saberwing C Programming Language 5 28-Dec-2006 14:57
ROMAN Numeral Pt. 2, Floating Point Exception SpyD3r C++ Forum 1 13-Nov-2005 00:02
Hex Result giving strange answers. Rosdahale C Programming Language 6 07-Dec-2004 20:28

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 07:09.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.