Hello,
I am aware that the computer stores a float in ieee. My question is how can i retrieve this ieee form of the number from the internal storage?
Thank you in advance.
Hello,
I am aware that the computer stores a float in ieee. My question is how can i retrieve this ieee form of the number from the internal storage?
Thank you in advance.
One way is to cast the floating-point variable to an integer and then use integer operations to access the three fields (see IEEE 754-1985 - Wikipedia, the free encyclopedia for how the fields are defined). For example, if you have a double d, you can cast it to an integer like this:
unsigned long long *double_as_int = (unsigned long long *)&d;
Then you can use shifting and masking operations to access the fields: the sign field is *double_as_int >> 63, the exponent field is double_as_int >> 52 & 0x7FF, and the fraction field is *double_as_int & 0x000FFFFFFFFFFFFFULL;
This method assumes that you have an unsigned long long that's 8 bytes long.
(For more details, see my article Displaying the Raw Fields of a Floating-Point Number - Exploring Binary)
yes i think that would work, but there is another way without actually doing the binary manipulations... I think I figured it out... you can use a union of the int and the float and the int willl be the ieee form of the float but I'm not sure what the union actually does or how it works....
Yes, union is another way to do this. It essentially does the same thing: it interprets the float storage as an integer. But you'll still need to do the bit manipulations if you want to access the IEEE fields (I assume that's what you're trying to do).
You could use bit fields in the union so that the floating point parts are already separated out for you: sign, exponent, significand. But you'll have to consider the bit order for your machine... which you'll need to figure out through experimentation. The program is not guaranteed to work on all platforms.
Last edited by nonoob; 10-04-2010 at 01:22 PM.
You're right, bit fields would work. The tradeoff is then bit manipulations vs dependence on endianness.