简体   繁体   English

内存中的浮点表示对我来说还不清楚

[英]floating point representation in memory is just not clear for me

My task was to get the fraction of a float then store it in an int. 我的任务是获取浮点数的一部分,然后将其存储在int中。 It seemed very easy. 看起来很容易。 I did this test: 我做了这个测试:

float f = 3.1415f;
printf("int pres. of float: %d\n"
       "int:                %d", *((int *)&f), 31415);

output: 输出:

int pres. of float: 1078529622

int: 31415

I changed them to base 2 to see where the 31415 is present. 我将其更改为2,以查看31415的位置。

0100 0000 0100 1001 0000 1110 0101 0110 - 3.1415
                    0111 1010 1011 0111 - 31415

I don't know what to do. 我不知道该怎么办。 How could I get the fraction as a simple integer? 我怎样才能得到分数作为一个简单的整数?

If we take 2.5, instead of 3.1415, because it's fairly easy to understand... 如果我们取2.5而不是3.1415,因为它很容易理解...

So your assumption is that 2.5 and 25 should have the same binary format. 因此,您的假设是2.5和25应该具有相同的二进制格式。 This is not the case. 不是这种情况。 25 = 0x19 = 11001. 2.5 = 10.1. 25 = 0x19 =11001。2.5 = 10.1。 Not at all the same thing. 完全不一样。

If you feel like doing the same sort of math for 3.1415, it goes something like this: 如果您想为3.1415做同样的数学运算,它会像这样:

3      = 11 (I can do that)
1/8    = 0.001  
0.1415 - 0.125 = 0.0165
1/64   = 0.000001
0.0165 - 0.015625 = 0.000875
1/2048 = 0.00000000001

And we still have some fractions of 0.1415 left to deal with at this point, but a rough result 11.00100100001. 现在,我们还需要处理0.1415的一部分,但粗略的结果是11.00100100001。

Now, if we compare your binary output (starting at the mantissa part), and inserting a decimal point, and take into account that floating point numbers "ignore the first one": 现在,如果我们比较您的二进制输出(从尾数部分开始),并插入一个小数点,并考虑到浮点数“忽略第一个”:

  11.00100100001
   1.00100100001110

Seems like my scribbles above aren't completely off... ;) 似乎我上面的涂鸦还没有完全消失...;)

Guess you need to start at https://en.wikipedia.org/wiki/IEEE_floating_point . 猜猜您需要从https://en.wikipedia.org/wiki/IEEE_floating_point开始。 This will tell you about the various representations of floating point numbers 这将告诉您有关浮点数的各种表示形式

There are two key complications. 有两个关键的并发症。 One is that float is a binary floating point type, so it cannot represent 3.1415f exactly. 一种是float是二进制浮点类型,因此它不能精确表示3.1415f。 All you have is an approximation. 您所拥有的只是一个近似值。 The closest exactly representable float value is 3.141499996185302734375. 可以精确表示的最接近的浮点值是3.141499996185302734375。

The other is that 3.1415f is in the range of normalized numbers, which means the most significant bit of the significand, if stored, would be a non-zero binary digit, so it is not stored. 另一个是3.1415f在归一化数字范围内,这意味着有效位的最高有效位(如果存储)将是一个非零的二进制数字,因此不会被存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM