• ### Popular Now

• 12
• 27
• 9
• 9
• 20

#### Archived

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

# Union of signed and unsigned types

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

## 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 on other sites
0011 1111 1000 0000 0000 0000 0000 0001 is the binary form of the floating point value 1.0f.

Read up on: IEEE Standard 754 Floating Point Numbers.
Wikipedia has also info

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

[edited by - dalleboy on February 27, 2004 2:43:26 PM]

thanks

##### Share on other sites
+-+--------+-----------------------+|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]