的值double
浮点类型表示如下:
可以看作两个32位整数;现在int
包含代码的所有版本(假设它是 32 位int
) 就是图中右边的那个,所以你最后所做的只是取尾数的最低 32 位。
Now, to the magic number; as you correctly stated, 6755399441055744 is 251 + 252; adding such a number forces the double
to go into the “sweet range” between 252 and 253, which, as explained by Wikipedia https://en.wikipedia.org/wiki/Double_precision_floating-point_format#IEEE_754_double-precision_binary_floating-point_format:_binary64, has an interesting property:
Between 252 = 4,503,599,627,370,496 and 253 = 9,007,199,254,740,992, the representable numbers are exactly the integers.
这是因为尾数为 52 位宽。
The other interesting fact about adding 251 + 252 is that it affects the mantissa only in the two highest bits—which are discarded anyway, since we are taking only its lowest 32 bits.
最后但并非最不重要的一点:标志。
IEEE 754 浮点使用幅度和符号表示,而“普通”机器上的整数使用 2 的补码算术;这里是如何处理的?
We talked only about positive integers; now suppose we are dealing with a negative number in the range representable by a 32-bit int
, so less (in absolute value) than (−231 + 1); call it −a. Such a number is obviously made positive by adding the magic number, and the resulting value is 252 + 251 + (−a).
Now, what do we get if we interpret the mantissa in 2’s complement representation? It must be the result of 2’s complement sum of (252 + 251) and (−a). Again, the first term affects only the upper two bits, what remains in the bits 0–50 is the 2’s complement representation of (−a) (again, minus the upper two bits).
由于将 2 的补码数减少到更小的宽度只需删除左侧的额外位即可完成,因此采用较低的 32 位可以在 32 位 2 的补码算术中正确给出 (−a)。