浮点数是如何由编译器表示和解释的。我试图理解这一点,以便能够轻松地解释字节数组对于浮点数和双精度数的含义。
谢谢
浮点数是如何由编译器表示和解释的。我试图理解这一点,以便能够轻松地解释字节数组对于浮点数和双精度数的含义。
谢谢
值得注意的是,std::numeric_limits
有一个 static bool const
成员变量 is_iec559
,仅适用于浮点类型。名称已经很明确了...
要真正解释它,您可能不想将其视为字节,因为尾数边界不与8位边界对齐。
大致如下:
mantisa = (*(unsigned int *)&floatVal) | MANTISA_MASK;
exp = ((*(unsigned int *)&floatVal) | EXP_MASK ) >> EXP_SHIFT;
sign = ((*(unsigned int *)&floatVal) | SIGN_MASK ) >> SIGN_SHIFT;
会让你拆开来玩弄果汁中心。
编辑:
#include <stdio.h>
void main()
{
float a = 4;
unsigned int exp,sign,mantisa;
int i;
for(i = 0;i<4;i++)
{
exp = (*((unsigned int *)&a) >>23) & 0xFF;
sign = (*((unsigned int *)&a) >>31) & 0x01;
mantisa = (*((unsigned int *)&a)) & 0x7FFFFF | 0x800000;
printf("a = %04x\r\n",*((unsigned int *)&a));
printf("a = %f\r\n",a);
printf("exp = %i, %02x\r\n",exp,exp);
printf("sign = %i, %02x\r\n",sign,sign);
printf("mantisa = %i, %02x\r\n\r\n",mantisa,mantisa);
a = -a / 2;
}
}
生成:
a = 40800000
a = 4.000000
exp = 129, 81
sign = 0, 00
mantisa = 8388608, 800000
a = c0000000
a = -2.000000
exp = 128, 80
sign = 1, 01
mantisa = 8388608, 800000
a = 3f800000
a = 1.000000
exp = 127, 7f
sign = 0, 00
mantisa = 8388608, 800000
a = bf000000
a = -0.500000
exp = 126, 7e
sign = 1, 01
mantisa = 8388608, 800000
Press any key to continue . . .