float f1 = 12.5;
float f2 = -12.5;
short int f = -1;//补码是16个1
int p = static_cast<int>(f);
int *p1 = reinterpret_cast<int *>(&f1);
int *p2 = reinterpret_cast<int *>(&f2);
cout << *p1 << endl; //1095237632
cout << *p2 << endl;//-1052246016
cout << p << endl;//因为最高位是1,所以高16位全补1,补码总共32个1,原码是-1
float 12.5:
32位
二进制:1100.1 ==》 1.1001 * 2 ^ 3
3 + 127 = 130
正数:补码和源码相同
1 8 23
0 1000 0010 1001 0000 0000 0000 0000 000(内存中)
用有符号int读取:1095237632
float -12.5:
原码应该是:
1 1000 0010 1001 0000 0000 0000 0000 000
用int 来读:
转成补码:减一取反(内存中)
1 0111 1101 0111 0000 0000 0000 0000 000
值是:-1,052,246,016
结论:将浮点数转换为内存中的的补码后,用int来读,直接读,而不再将负数转换为原码。
从数值到计算机中,+127;从内存转出来,-127.
测试:
float f = -0.25;
int *p = reinterpret_cast<int *>(&f);
cout << *p << endl;//-1 098 907 648
-0.25:原码:1 0111 1101 +23个0
补码:1 1000 0011 +23个0
直接读补码:-1,098,907,648
1 1000 0011 0000 0000 0000 0000 0000 000