计算机内部浮点型和整型的存储规则

浮点型:按照IEEE754标准存储

整型:按照补码存储

#include 

int main()
{
    float a = 1234.1234;  /* 1,234.1234130859375 23位 精度10^-5*/
    printf("this is float:0x%0x\n", *(unsigned *)&a); 
    /* 0(+) 10001001(137 -127 = 10, 2^10 = 1024) 00110100100001111110011 (1721331 / 2^23 + 1 = 1.20519864559173583984375)*/

    float b = -1234.1234; 
    printf("this is float:0x%0x\n", *(unsigned *)&b); 
    /* 1(-) 10001001(137 -127 = 10, 2^10 = 1024) 00110100100001111110011 (1721331 / 2^23 + 1 = 1.20519864559173583984375)*/

    double c = 1234.1234; /* 1,234.123399999999946885509416461 52位 精度10^-14 多9位*/
    printf("this is double:0x%0llx\n", *(unsigned long long*)&c); 
    /* 0(+) 10000001001(=10) 0011010010000111111001011100100100011101000101001110(52位 =1.20519863281249994813038028951269) */
    
    int d = -1;
    printf("this is int:0x%0x\n", *(unsigned *)&d);
}

运行结果:

this is float:0x449a43f3
this is float:0xc49a43f3
this is double:0x4093487e5c91d14e
this is int:0xffffffff

 浮点型:将输出的8个16进制数字转为32位2进制数(如代码中注释所示),按照IEEE754标准划分该二进制数(1位符号,8位移码表示的阶码,23位原码表示的尾数,如代码注释中所示),可以还原出该二进制数(如代码注释中所示)。

整型:`0xffffffff`是`-1`的补码。

附:代码的实现思路

获取浮点型和整型变量的指针,将其当作无符号数打印出来

你可能感兴趣的:(c++,c语言)