首页 > 解决方案 > 在c#中从二进制值转换为双精度时出错

问题描述

我正在尝试读取由c++程序制作的二进制文件。这个文件有一些数字,当我试图读取它们时,我得到了一个错误的值。double double

这是从文件中读取的 HEX 值:

00-67-CC-02-B3-F7-40-CA

期望值

0.2051076530529798

实际值:

-4.9596277989715114E+49

二进制文件类型:double 8字节(c++

c#中的转换输出:( double)binaryreader.ReadDouble()

这是代码:

reader = new BinaryReader(File.Open(path, FileMode.Open), Encoding.Default);

double value = reader.ReadDouble();

我已经检查过了,我在正确的位置使用了这个命令。为什么我有这个不同的价值

标签: c#c++binaryreader

解决方案


让我们看看expectedrepesented as bytes:

double expected = 0.2051076530529798;

string result = string.Join("-", BitConverter
  .GetBytes(expected)
  .Select(b => b.ToString("X2")));

Console.WriteLine(result);

结果:

66-CC-02-B3-F7-40-CA-3F

让我们其与您的输入进行比较:

00-67-CC-02-B3-F7-40-CA    // Your input 
   66-CC-02-B3-F7-40-CA-3F // Should be for 0.2051076530529798

看来您应该跳过 1 字节(您在错误的位置读取流)。

// I've assumed that the next byte is `3F`
// Your input without starting `00` but with final `3F`
string data = "67-CC-02-B3-F7-40-CA-3F";

double value = BitConverter.ToDouble(data
    .Split('-')
    .Select(item => Convert.ToByte(item, 16))
    .ToArray(), 
  0);

Console.Write(value);

结果:

 0.20510765305298   

推荐阅读