floating point - Convert hex to float in C -


i have hexdecimal no. string , want convert float. can suggest idea? searched here in forum , got 1 post mentioning following solution. understood first string converted hex number , hex no converted float. didn't understand how float_data = *((float*)&hexvalue); taking place. , code not work method too.

correction 1: think didn't mention here. sorry this. hex value 39 39 2e 30 35 when converted ascii, gives 99.05. , need ascii float no. following code:

#include <stdlib.h> #include <string.h> #include <stdio.h> int main() {     char *my_data;     double float_data;     unsigned int hexvalue;     my_data = malloc (100);     my_data =strcpy(my_data, "39 39 2e 30 35");     sscanf (my_data, "%x", &hexvalue);     float_data = *((float*)&hexvalue);     printf ("the floating n. %f", float_data);     free (my_data);     return 0; } 

scan using "%hhx" character array, append null character , convert float using atof() or strtod().

int main(void) {   unsigned char uc[5+1];   sscanf("39 39 2e 30 35", "%hhx%hhx%hhx%hhx%hhx", &uc[0], &uc[1], &uc[2], &uc[3], &uc[4]);   uc[5] = 0;   float f = atof(uc);   printf("%f\n", f);   return 0; } 

output

99.050003 

[edit] available since c99, scanf():

hh specifies following d, i, o, u, x, x, or n conversion specifier applies argument type pointer signed char or unsigned char. c11dr §7.21.6.2 11


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -