1.规格化的值
以sizeof(float)=4为例:
1.5的浮点数表示:
1)1.5转换为2进制:1.1
2)转换:0.1*2^0 (整数部分的1省略)
3)得到阶码:127+0=127,即0111 1111 (指数部分可能是负数,为了兼容负数,需要+127)
4)得到尾数:1,后面补齐0
5)确定符号位:0
所以,1.5的浮点数表示如下:
符号位:1bit | 阶码:8bits | 尾数:23bits |
0 | 0111 1111 | 1000 0000 0000 0000 0000 000 |
程序验证如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float f = 1.5;
printf("%x", *(int*)&f);//打印3fc00000
return 0;
}
3fc00000即:
0 01111111 1000 0000 0000 0000 0000 000
一致!
2.非规格化的值
即,所有的阶码都是0
符号位:1bits | 阶码:8bits | 尾数:23bits |
x | 0000 0000 | xxxx xxxx xxxx xxxx xxxx xxx |
用途有2:
1)提供了一种表示值0的方法
2)表示那些非常接近于0.0的数,对“逐渐溢出”属性的支持
代码示例:
////小端模式机器实验
#include <stdio.h>
#include <stdlib.h>
typedef struct _float
{
int w:23;
int j:8;
int s:1;
}Float;
int main()
{
float f = 0;
Float obj;
obj.s = 0;
obj.j = 0;
obj.w = 0x400000;
f = *(float*)(&obj);
printf("%f", f);//输出0.000000
return 0;
}
3.无穷大
符号位:1bits | 阶码:8bits | 尾数:23bits |
x | 1111 1111 | 0000 0000 0000 0000 0000 000 |
代码示例:
#include <stdio.h>
#include <stdlib.h>
typedef struct _float
{
int w:23;
int j:8;
int s:1;
}Float;
int main()
{
float f = 0;
Float obj;
obj.s = 0;
obj.j = 0xff;
obj.w = 0x0;
f = *(float*)(&obj);
printf("%f", f);//输出inf
return 0;
}
4.NaN
符号位:1bit | 阶码:8bits | 尾数:23bits |
x | 1111 1111 | 非全0 |
代码示例:
#include <stdio.h>
#include <stdlib.h>
typedef struct _float
{
int w:23;
int j:8;
int s:1;
}Float;
int main()
{
float f = 0;
Float obj;
obj.s = 0;
obj.j = 0xff;
obj.w = 0x1;
f = *(float*)(&obj);
printf("%f", f);//输出nan
return 0;
}