C++浮點數的結構分解

#include <iostream>
#include <iomanip>

using namespace std;

ostream& ShowHex(ostream& out, int val)
{
  return out << "0x" << hex << setfill('0') << setw(8) << val;
} 

int main()
{
    union{
          long a;
          float b;          
    } foo ;
    
    cout << sizeof(long) << " " << sizeof(float) << " " << sizeof(foo) <<endl << endl;
    
    // zero
    foo.b = 0.0;
    cout << "Number: " << foo.b << " HEX="; ShowHex(cout, foo.a) << endl;
    cout << "Sign bit: "; ShowHex(cout, (foo.a>>31)&0x01) << endl;
    cout << "Exp bits: "; ShowHex(cout, (foo.a>>23)&0xFF) << " Val=" << dec << ((foo.a>>23)&0xFF) << endl; 
    cout << "Frac bit: "; ShowHex(cout, foo.a&0x400000) << endl << endl;

    // positive float            
    int cnt = 0;
    for (foo.b=1 ; foo.b/2.0!=0 && cnt<10 ; foo.b/=2.0, ++cnt)
    {
        cout << "Number: " << foo.b << " HEX="; ShowHex(cout, foo.a) << endl;
        cout << "Sign bit: "; ShowHex(cout, (foo.a>>31)&0x01) << endl;
        cout << "Exp bits: "; ShowHex(cout, (foo.a>>23)&0xFF) << " Val=" << dec << ((foo.a>>23)&0xFF) <<endl; 
        cout << "Frac bit: "; ShowHex(cout, foo.a&0x400000) << endl << endl;
    }
    cout << endl;
    
    // negative float 
    cnt = 0;
    for (foo.b=-1 ; foo.b/2.0!=0 && cnt<10 ; foo.b/=2.0, ++cnt)
    {        
        cout << "Number: " << foo.b << " HEX="; ShowHex(cout, foo.a) << endl;
        cout << "Sign bit: "; ShowHex(cout, (foo.a>>31)&0x01) << endl;
        cout << "Exp bits: "; ShowHex(cout, (foo.a>>23)&0xFF)<<" Val=" << dec << ((foo.a>>23)&0xFF) << endl;
        cout << "Frac bit: "; ShowHex(cout, foo.a&0x400000) << endl << endl;
    }
    
    return 0;
}

留言