Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

nathan123

Union of signed and unsigned types

This topic is 5229 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

#include <iostream>
using namespace std;

union Test
{
	float fValue;
	unsigned int uiValue;
};

//-----------------------------

int main()
{
Test t;
t.fValue=1;
cout<<"t.fValue: "<<t.fValue<<" t.uiValue "<<t.uiValue<<"\n";
return 0;
}//end of main



The output is as follows: t.fValue 1 t.uiValue: 1065353217 My question is, why are these values different? Why aren''t both values 1? I know this probably has to do with the fact that one is signed and the other is unsigned, but I guess I dont understand how it all works. For example, I thought (now I realize I''m probably wrong) that when I set t.fValue to 1, its stored as the following binary: 0000 0000 0000 0000 0000 0000 0000 0001 So, I thought that because unions share memory, when the above is accessed through t.uiValue, the value would also be 1 and the only time I would get a difference between t.fValue and t.uiValue is when I set t.fValue to a negative number. Can someone please explain what is happening? (If it helps in an explanation, 0011 1111 1000 0000 0000 0000 0000 0000 is the other number, 1065353217 in binary form). Thanks for your help.

Share this post


Link to post
Share on other sites
Advertisement

+-+--------+-----------------------+
|0|01111111|00000000000000000000001|
+-+--------+-----------------------+
|S| Exp    | Fraction              |
+-+--------+-----------------------+
S - Sign (0 = +, 1 = -)
Exp - Exponent (bias +127)

And that is correct 1.0f = Sign Fraction ^ Exponent = + 1 ^ (127 - 127) = + 1 ^ 0 = 1.

[How To Ask Questions|STL Programmer''s Guide|Bjarne FAQ|C++ FAQ Lite|C++ Reference|MSDN]

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!