LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   ASCII to float (https://www.linuxquestions.org/questions/programming-9/ascii-to-float-392620/)

lucky6969b 12-14-2005 12:27 AM

ASCII to float
 
Hi,
if I have a string say
C203145B (32-bit)
I want to convert it to a float
My attempt was

long temp;
float ret;
long *cast;

cast = (long *) &ret;
unsigned int idx = DataIndex * 8;

temp = (long) AsciiToHex (m_pData[idx]) << 28 |
(long) AsciiToHex (m_pData[idx+1]) << 24 |
etc

*cast = temp;
return ret;

it is working well in Windows but return a small fraction number in Linux.... Is it some big/small endian problems here?
Thanks
Jack

Hko 12-14-2005 11:23 AM

Code:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

double hex2double(const char *hex)
{
    char *tmp;
   
    if ((tmp = malloc(strlen(hex) + 3)) == NULL) {
        perror("hex2double()");
        exit(1);
    }
    if (hex[0] != '0' || hex[1] != 'x' || hex[1] != 'X') {
        sprintf(tmp, "0x%s", hex);
    } else {
        strcpy(tmp, hex);
    }
    return atof(tmp);
}

int main()
{
    double floatnum;

    floatnum = hex2double("C203145B");
    printf("Resulting double value = %f\n", floatnum);
    return 0;
}

Output:
double value = 3254981723.000000

ppanyam 12-15-2005 01:51 AM

How about this?

union hex2str{
float f;
char ch[4];
} h2s;

strcpy(ret,h2s.ch);
printf("%f",h2s.f);

You may have to flip the ch[0] with ch[3], ch[1] with ch[2] depending on your system's byte order.

lucky6969b 12-15-2005 02:52 AM

Thanks for waking me up.
Jack


All times are GMT -5. The time now is 11:36 PM.