c - 二进制数表示

标签 c binary floating-point computer-architecture

首先,这不是精度或类似问题。

我的问题是,编译器如何决定如何表示数字?

我们以C为例。我写

double d = 4.5632;

它如何选择二进制表示?我知道它没有准确表示,那么它如何选择最接近的可表示数字呢?它是在编译时完成的吗?是由 CPU 还是 OS 完成的?

仅在您知道这是如何发生的情况下回答,“不用担心”之类的回答没有帮助。此外,“这取决于平台”也没有帮助,您可以选择一个平台并对此进行解释。

最佳答案

编译器不决定(通常)。 CPU(通常)有一个浮点单元,它要求浮点值以特定格式表示(通常是 IEEE-754 )。当然,可以模拟完全不同的体系结构,在这种情况下,编译器/模拟器作者可以自由选择完全不同的表示形式。但这并不典型。

至于具体词法表示4.5632如何转换为底层表示,那是C标准规定的。因此,从 C99 标准的第 6.4.4.2 节(我突出显示了最相关的部分):

The significand part is interpreted as a (decimal or hexadecimal) rational number; the digit sequence in the exponent part is interpreted as a decimal integer. For decimal floating constants, the exponent indicates the power of 10 by which the significand part is to be scaled. For hexadecimal floating constants, the exponent indicates the power of 2 by which the significand part is to be scaled. For decimal floating constants, and also for hexadecimal floating constants when FLT_RADIX is not a power of 2, the result is either the nearest representable value, or the larger or smaller representable value immediately adjacent to the nearest representable value, chosen in an implementation-defined manner. For hexadecimal floating constants when FLT_RADIX is a power of 2, the result is correctly rounded.

这将在编译时完成(尽管标准没有强制要求)。

关于c - 二进制数表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10364390/

相关文章:

c++ - fp :precise vs. fp: 严格性能

c - C 中空格等于 '\0' 吗?我怎样才能避免混淆它们?

c - 在递增时将字符值保持在 '0 and ' 9' 之间

c - 如何基于数组中的输入值打印星号

c - 根据条件无法访问

java - 在java中将 float 舍入到下一个整数值

java - 算二元递归吗?

mysql - 可移植的MongoDB和MySQL/PostgreSQL二进制文件

c# - 将字符串转换为二进制零和一

C中计算 float 的范围