简体   繁体   English

C#和C / C ++中二进制到浮点转换之间的区别

[英]Difference between binary to float conversion in C# and C/C++

When converting a binary number in C/C++ and C# we're getting 2 different results by its rounding. 在C / C ++和C#中转换二进制数时,通过四舍五入得到2个不同的结果。 For example - let's take 1000010000010110110000010111111 , in C# - we would get 34.84448 while we would get 34.844479 , why is this minor difference? 例如-让我们拿1000010000010110110000010111111在C#中-我们将获得34.84448而我们将获得34.844479 ,为什么会有这么小的差异? Converting in C#: 在C#中转换:

float f = System.BitConverter.ToSingle(bytearray,0);
//bytearray is an array that contains our binary number

in C++: 在C ++中:

int a = 1108041919; //The number that is being represented
float f = *(float *)&a;

There are many ways to unambiguously represent the same floating point value in decimal. 有很多方法可以明确地以十进制表示相同的浮点值。 For example, you can add arbitrarily many zeros after the exact output (note that since each power of two has a decimal representation of finite length, so does every floating point number). 例如,您可以在精确输出之后任意添加多个零(请注意,由于2的每个幂均具有有限长度的十进制表示形式,因此每个浮点数也是如此)。

The criterion for "when can I stop printing extra digits" is usually chosen as "you can stop printing extra digits when you would get the exact same value back if you parsed the decimal output into a float again". 通常选择“何时可以停止打印多余的数字”的标准是:“如果将十进制输出再次解析为浮点数,则当您获得完全相同的值时,可以停止打印多余的数字”。 In short: It is expected that outputting a float "round-trips". 简而言之:期望输出一个浮点数“往返”。

If you parse the decimal representations 34.844479 and 34.84448 , you will find that they both convert back to the floating point value 0x420b60bf or 01000010000010110110000010111111 . 如果解析十进制表示形式34.84447934.84448 ,则会发现它们都转换回浮点值0x420b60bf01000010000010110110000010111111 So both these strings represent the same floating point number. 因此, 这两个字符串都表示相同的浮点数。 (Source: Try it yourself on https://www.h-schmidt.net/FloatConverter/IEEE754.html ) (来源:在https://www.h-schmidt.net/FloatConverter/IEEE754.html上尝试一下)

Your question boils down to "Why do the different runtime libraries print out different values for the same float?", to which the answer is "it's generally up to the library to figure out when to stop printing digits, they are not required to stop at the bare minimum". 您的问题归结为“为什么不同的运行时库为同一个浮点数打印出不同的值?”,答案是“通常由库确定何时停止打印数字,而不必停止数字输出。最少”。 As long as you can get the same float back when you parse it again, the library did its job. 只要您再次解析它时可以返回相同的浮点数,库就可以完成它的工作。

If you want to see the exact same decimal strings , you can achieve that with appropriate formatting options. 如果您希望看到完全相同的十进制字符串 ,则可以使用适当的格式设置选项来实现。

由于值是相同的,我们可以猜测正在处理该值的打印功能可能在那儿有细微差别:-)

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

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