I have a 32 bit unsigned value that I want to convert to ieee 754 floating point.
Here are my variables:
unsigned int val = 0x3f800000;
float floatVal;
I know that I have to do the following to be able to properly cast the uint value to the ieee 754 floating point value I expect of 1.0
floatVal = *((float*)&val);
Can anyone explain why floatVal = (float)val does not return the same result? Instead of 1.0 floatVal gets a value of 1.0653532e+009. I believe it is partially due to the fact that bits are lost during this type of typecasting whereas the bits are preserved through pointer casting but a more detailed explanation would be much appreciated.
intis 32 bit on a little endian machine. just tested here. but you should use memcpy to avoid violating the strict aliasing rule. you should use stdint & test endianness before attempting to convert. - Jean-François Fabre♦floatandunsignedrepresent values differently. Depends what you are trying achieve. To convert the value (e.g. so2Uconverted tofloatwill have the value2.0f) then use(float)val. To get a float that has the same binary representation (but, almost certainly different value) use*((float *)&val)(bear in mind the latter ASSUMESfloatis andunsignedare the same size and will not work as you describe for implementations that use non-IEEE floating point). - Peter