简体   繁体   English

C#中的十六进制到浮点转换

[英]Hex to Float Conversion in C#

I have a hex value 0x492655FE that want to convert to float. 我有一个要转换为浮点数的十六进制值0x492655FE。 My code is 我的代码是

uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
byte[] floatVals = BitConverter.GetBytes(num);
BitConverter.ToSingle(floatVals, 0).Dump();

Result: 681311,9 结果:681311,9

But in ModbusPoll program : display float inverse result: 681311,8750 但是在ModbusPoll程序中:显示浮点运算反结果: 681311,8750

I tried another code. 我尝试了另一个代码。 But result is same. 但是结果是一样的。 What can I do for this problem? 我该怎么办?

According to this 0x492655FE in single-precision represents exactly 6.81311875E5 or 681311.875 in decimal. 根据 0x492655FE,单精度精确地代表6.81311875E5或681311.875(十进制)。 If you print more digits after the radix point you'll get the same output 如果您在小数点后打印更多数字,您将获得相同的输出

However float has only 23 bits of mantissa which corresponds to ~6-7 decimal digits of precision. 但是float仅尾数有23位,相当于精度的6-7十进制数字。 The rest are generally just noise because powers of 2 cannot represent exactly numbers in fractional numbers in decimal, thus it's safe to round to only the first 6-7 digits 其余的通常只是噪声,因为2的幂不能精确表示十进制小数形式的数字,因此可以安全地舍入到前6-7个数字

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

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