简体   繁体   中英

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. For example - let's take 1000010000010110110000010111111 , in C# - we would get 34.84448 while we would get 34.844479 , why is this minor difference? Converting in C#:

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

in 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).

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 . So both these strings represent the same floating point number. (Source: Try it yourself on 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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