float/double 文字如何存储在已编译的 .NET DLL 文件中?

How are float/double literals stored in compiled .NET DLL files?

我的应用程序必须在所有机器上产生完全相同的数字结果。我知道 C# 中的 float/double 数学不是确定性的,但是文字值的二进制表示如何?

float x = 1.23f;

编译后的DLL文件中1.23f如何存储?作为 32 位 IEEE-754 格式浮点数的二进制表示?或者作为一些中间表示,需要通过目标机器上的抖动(潜在的不确定性来源)转换为 IEEE-754 浮点数?

我明白为什么 C# 中的浮点运算不是确定性的。我只问文字的二进制表示是否是确定性的。拜托,没有关于一般浮点确定性的答案。

为此引入了小数类型。在此处的官方 Microsoft 文档中查看。 https://docs.microsoft.com/en-us/dotnet/api/system.decimal?view=netframework-4.8

A decimal number is a floating-point value that consists of a sign, a numeric value where each digit in the value ranges from 0 to 9, and a scaling factor that indicates the position of a floating decimal point that separates the integral and fractional parts of the numeric value.

The binary representation of a Decimal value consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the 96-bit integer and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10, raised to an exponent ranging from 0 to 28. Therefore, the binary representation of a Decimal value the form, ((-296 to 296) / 10(0 to 28)), where -(296-1) is equal to MinValue, and 296-1 is equal to MaxValue. For more information about the binary representation of Decimal values and an example, see the Decimal(Int32[]) constructor and the GetBits method.

The scaling factor also preserves any trailing zeros in a Decimal number. Trailing zeros do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeros might be revealed by the ToString method if an appropriate format string is applied.

它们以 IEEE 754 格式存储。

您可以通过使用 ILDASM.EXE 反汇编生成的代码并检查二进制值来验证这一点。

例如,float x = 1.23f; 将生成:

IL_0000:  /* 22   | A4709D3F         */ ldc.r4     1.23

(请注意,这在 Intel 平台上以小端格式存储。)