I am new to programming, I’ve done web development, but I am currently trying to learn real programming. The question I have is already answered here.
union ufloat {
float f;
unsigned u
};
ufloat u1;
u1.f = 0.3f;
What I don’t get is how it works. What does the 0.3 part do? I couldn’t find it in my text. And how does this convert a float to binary? Because cout<<u1.u; doesn’t seem to give me the answer. Can someone help?
0.3is just a test value. Printingu1.uwill not give you the binary representation, but the value of the binary representation interpreted as a base 10 integer. To get the binary value, you have to convertu1.uto binary.Another way you can do the conversion is by using bitwise operators.
For example:
Note that this will print the bits in reverse order (least significant first). I’ll leave it up to you to fix this (you can use recursion or store values in an array and then print the array reversed).
I also suggest you read about unions. Basically, the
unsignedwill occupy the same memory space as thefloat, allowing you to circumvent the restrictions of using bitwise operators to find the binary representation of thefloat.