This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Convert an array of characters to float

I have got a problem with my funtion to convert an array to float. I use the "Debug" to see the value of my variables. The problem is in the multiplication on the second element of array fd[1] only when there is a "7","8" or "9", for example to convert "070000" the value of bux=4464, for others value the funtion works perfectly.

float Conv_C2F_FE(unsigned char fd[6])
{float bux;
 bux=(fd[0]-0x30)*100000;
 bux=bux+(fd[1]-0x30)*10000;
 bux=bux+(fd[2]-0x30)*1000;
 bux=bux+(fd[3]-0x30)*100;
 bux=bux+(fd[4]-0x30)*10;
 bux=bux+(fd[5]-0x30);
 return bux;
}
Hope somebody can help me. Thanks.

Parents
  • "because if i do 6.8*10000 the funtion works"

    But that is a floating-point expression, isn't it?

    "do you thing that could be a mistake of C51?"

    No it's a mistake in your code.

    Remember, the 'C' programming language assumes that everything is an int unless stated otherwise.

    10,000 can be expressed as an int, so it will be evaluated as an int;
    (fd[1]-0x30) will be promoted to int, then the expression

    bux=bux+(fd[1]-0x30)*10000;
    will be evaluated as an int.

    In C51, an int is 16 bits - so the expression will clearly overflow for values of fd[1] greater than '6'

    You need to force the compiler to evaluate this expression as a long:
    bux=bux+(fd[1]-0x30)*10000L;
    So, back to the excercise, can you now explain why you didn't get the problem multiplying by 100,000...?
    And also why 6.8*10000 works?

Reply
  • "because if i do 6.8*10000 the funtion works"

    But that is a floating-point expression, isn't it?

    "do you thing that could be a mistake of C51?"

    No it's a mistake in your code.

    Remember, the 'C' programming language assumes that everything is an int unless stated otherwise.

    10,000 can be expressed as an int, so it will be evaluated as an int;
    (fd[1]-0x30) will be promoted to int, then the expression

    bux=bux+(fd[1]-0x30)*10000;
    will be evaluated as an int.

    In C51, an int is 16 bits - so the expression will clearly overflow for values of fd[1] greater than '6'

    You need to force the compiler to evaluate this expression as a long:
    bux=bux+(fd[1]-0x30)*10000L;
    So, back to the excercise, can you now explain why you didn't get the problem multiplying by 100,000...?
    And also why 6.8*10000 works?

Children