This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Type casting integer to float ?

Dear Members,

I want to convert uint32_t to float, the code :

unsigned int dat = 2248;
	float float_val;
	
	

    float_val = (double)(dat);                         
    NRF_LOG_INFO( "float_val = %.3f\n", float_val );  

It's returning nothing, what is missing here ?

Thanks

Parents Reply Children
  • From terminal  :

    <info> app: Float number: 0.000
                                                   

                                   
                                                  

    nfo> app: Float number V2:
                 

    Code : 

    	uint32_t int_value;
    	float float_val;
    	
           
        //float_val = *(float *)&int_value;	
        memcpy(&float_val, &int_value, sizeof(int_value));
    	  NRF_LOG_INFO("Float number: "NRF_LOG_FLOAT_MARKER"\n\r",NRF_LOG_FLOAT(float_val));
    	  NRF_LOG_INFO("Float number V2: %.2f",float_val);

  • Float in c is IEEE754 format. 1st bit represent sign, the next 8 bits represent expo and the rest 23 bits 

    represent fraction. The uint32_t you try is 2248 that the expo is 0. Try this

    float x = 1.1;

    uint32_t int_value = *(uint32_t *)&x;

    //int_value is 1066192077

    float y = *(float *) &int_value; 

    Or use memcpy, the effect is the same.

Related