int to float conversion
I'd like to convert 32int into float value.
Direct cast does not work in a way I expected.
in hex BFFFF2E5
singned int -1073745179
When I cast
I got -1.073745e+09
myFloat = (float)myInt ;
Value I expect is:
float :-1.999600e+00 (from GHex or other hex editor)
How to get this value in C code?
Conversion of int to float does not generally do a bitwise copy. It converts the value put in. -1073754179 is approximately equal to -1.073...e+9.
A simple way to get the result you expect (assuming int and float are the same size - not always true)
There are alternatives involving pointer abuse, but those things are dangerous in hands of children.
memcpy(&myFloat, &myInt, sizeof(int));
You are telling the compiler to take the number you have (large integer) and make it into a float, not to interpret the number AS float. To do that, you need to tell the compiler to read the number from that address in a different form, so this:
That means, if we take it apart, starting from the right:
myFloat = *(float *)&myInt ;
&myInt - the location in memory that holds your integer.
(float *) - really, I want the compiler use this as a pointer to float, not whatever the compiler thinks it may be.
* - read from the address of whatever is to the right.
myFloat = - set this variable to whatever is to the right.
So, you are telling the compiler: In the location of (myInt), there is a floating point number, now put that float into myFloat.
As grumpy says: This is a "sharp weapon", and it CAN do harmful things if you use it wrong.
Create a union containing a 32-bit integer and a float.
The int and float are now just different ways of looking at the same bit of memory;
// float is -1.999600
my_union.myInt = 0x BFFFF2E5;
printf("float is %f\n", my_union.myFloat);
Byte order machine differences may rear its ugly head.
Would also turn out troublesome if sizeof(int) differed from sizeof(float).
Byte order should be the same for int as for float in all modern machines. I think PDP-11 was storing floating point in "middle endian", so the low bits were in the middle of the 32-bit word. But that is a rather unusual setup, and I'm not aware of any processor architecture designed in the last 20 years that does so (someone will of course immediately pop out of the woodwork to prove that I'm not aware of ALL processors designed in the last 20 years, but that is life).
Originally Posted by nonoob
The size problem that onionknight points out is a different story. If sizeof(int) != sizeof(float) then you have a problem with ALL of the suggested techniques, because they all assume that we load a float from the memory held by an integer value, and if they are not the same size, obviously bad things will happen.