Jump to content
  • Advertisement


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


Union of signed and unsigned types

This topic is 5406 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;
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

|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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!