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.
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.
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.
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.
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 .
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With