Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to float: how it is done

I'm new to C programming language, and I'd like to ask a question.

Integer i here is casting to float then f (somehow) successfully represents 5.0:

int i = 5;
float f = i;   //Something happened here...

However if we try this approach:

int i = 5;
float f = *(float *)&i;

f would NOT get 5.0 since it interprets the bits stored in i in "float's way". So what magic the complier actually does in the first case? It seems a quite effort-taking job... Can someone specify that? Thanks.

like image 208
Xu Hong Avatar asked Jul 20 '12 15:07

Xu Hong


People also ask

How do you convert int to float?

To convert an integer data type to float you can wrap the integer with float64() or float32. Explanation: Firstly we declare a variable x of type int64 with a value of 5. Then we wrap x with float64(), which converts the integer 5 to float value of 5.00.

How do you convert input to float?

You can use the float() function to convert any data type into a floating-point number. This method only accepts one parameter. If you do not pass any argument, then the method returns 0.0. If the input string contains an argument outside the range of floating-point value, OverflowError will be generated.

How does the int function convert a float to an int?

To convert a float value to int we make use of the built-in int() function, this function trims the values after the decimal point and returns only the integer/whole number part.

Can an int become a float?

Yes, an integral value can be added to a float value. The basic math operations ( + , - , * , / ), when given an operand of type float and int , the int is converted to float first. So 15.0f + 2 will convert 2 to float (i.e. to 2.0f ) and the result is 17.0f .


2 Answers

convert int bits to float

float IntBitsToFloat(long long int bits)
{
    int sign     = ((bits & 0x80000000) == 0) ? 1 : -1;
    int exponent = ((bits & 0x7f800000) >> 23);
    int mantissa =  (bits & 0x007fffff);

    mantissa |= 0x00800000;
   // Calculate the result:
   float f = (float)(sign * mantissa * Power(2, exponent-150));
   return f;
}
like image 73
Pankaj Kumar Boora Avatar answered Oct 12 '22 00:10

Pankaj Kumar Boora


Well, I just compiled the code in question under VC++ and looked at the disassembly:

   int i = 5;
00A613BE  mov         dword ptr [i],5 

   float f = i;
00A613C5  fild        dword ptr [i] 
00A613C8  fstp        dword ptr [f] 

First assembly statement moves 5 into the memory represented by i. Second statement, fild, converts the memory represented by i into a floating point number and pushes it onto the FPU stack. The third statement, fstp, takes the memory on the FPU stack and moves it to f.

like image 23
Joseph Willcoxson Avatar answered Oct 12 '22 02:10

Joseph Willcoxson