float型,和double型的存储格式,如图
验证计算:
float fnum = 1.123456;
int f2n = *(int*)&fnum;
cout << fnum << endl;
cout << hex << f2n << endl;
cout << dec;
int strnum[32];
int i;
for ( i=0; i<32; i++ )
{
strnum[i] = f2n & 0x00000001;
f2n = f2n>>1;
}
//show 32bits binary
for ( i=31; i>=0; i-- )
{
if ( i == 30 || i == 22 )
cout << " ";
cout << strnum[i];
}
cout << endl;
//M 23-31 8位 (0-255)
int m = 0;
int weight = 1;
for ( i=23; i<=31; i++ )
{
m += strnum[i] * weight;
weight *= 2;
}
cout << "m=" << m << endl;
//f 0-22 23位
double f = 0;
double fracweight = 0.5;
for ( i=22; i>=0; i-- )
{
f += strnum[i] * fracweight;
fracweight /= 2;
}
cout << "f=" << f << endl;
//calc result
double result1 = (1+f)*pow(2.0,m-127);
cout << "result = 1.f * 2^(e-127)" << endl;
cout << result1 << endl;
以上只验证s为0,0<e<255,的情况
下面引用特殊值的情况
其中在float型,单精度情况下,Emin=-126,Emax=+127,格式如下
具体参考一片论文,David Goldberg (March 1991). "What Every Computer Scientist Should Know About Floating-Point Arithmetic". ACM Computing Surveys 23 (1): 5–48.
另有IEEE Standard 754 Floating Point Numbers