Desperately need help with C!!
Desperately need help with C!!
(OP)
I have a program which calls a function in a library. The function returs a 4 byte character array which contains a (BFP32) binary floating point 32 bit value. I can not seem to get the floating point value out of this 4 byte string. Does anyone have a clue as to how I could go about doing this?
Cameron
Cameron





RE: Desperately need help with C!!
Let's say you have:
char *toto(); //which is the function returning the floating value as a char *
And let's say you call toto from main:
main()
{
char *cPtr; // pointer to char array
float *fPtr; // pointer to float value for conversion purposes
float value; // resulting value
...
cPtr = toto();
fPtr = (float *) cPtr; // fool the language telling it the char pointer is a float pointer
value = *fPtr; // retrieve the value from the pointer
...
}
Putting it all in the same line is possible but would be more encryptic (so I didn't do it!)
It is a little bit tricky, but a function returning a float in a char array is more than tricky.
You could also use an union which MAY work as well...
TiL
RE: Desperately need help with C!!
extern int rd123fld(FILE *, char *, char *, char *, long *, int *)
The actual function is:
int rd123sfld(fp,tag,leadid,rd_str,str_len,status)
FILE *fp ;
char *tag ;
char *leadid;
char *rd_str;
long *str_len;
int *status;
char *rd_str is the one which returs the "float" value.
In my main program there is a string defined as:
char string[5000]
later in the code the function is called like this:
if (! rd123sfld
(fpin, /* file pointer */
tag, /* field tag returned */
&leadid, /* leader identifier returned */
string, /* subfield contents returned */
&str_len, /* string length */
&status)) /* status returned */
{
printf ("\nERROR READING DATA RECORD SUBFIELD");
goto done;
}
I then need to convert the first 4 bytes of string to the float value.
I'll try what you suggested, but if you can provide any further suggestions, that would be great. I didn't write this code, and the guy who did sied last year. I've been given the task of fixing it. I appreciate the help.
Cameron
RE: Desperately need help with C!!
If your problem is still not solved, here is my feedback.
Once you got your value in string[], you can do the following:
float fVal;
float fPtr;
fPtr = (float *) string; // get a float pointer to point at the 4 bytes in the string
fVal = *fPtr; // get the value pointed by the float pointer
here fVal contains your value!
I hope you are not getting the float value in ascii format because then you'll rather need to use fVal = (float) strtod(string);
Good luck!
TiL