3

I'm trying to read a binary file made from a c++ program. This file has some double numbers and, when I tried to read them, I get a wrong double value.

This is the HEX value read from the file:

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

Expected value:

0.2051076530529798

Actual value:

-4.9596277989715114E+49

Binary file type: double 8 byte (c++)

Conversion output in c#: double (binaryreader.ReadDouble())

This is the code:

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

double value = reader.ReadDouble();

I already checked, i'm using this command in the right position. Why do I have this different value?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Tode93
  • 33
  • 3

2 Answers2

6

Let's have a look at the expected repesented as bytes:

double expected = 0.2051076530529798;

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

Console.WriteLine(result);

Outcome:

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

Let's compare it with your input:

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

It seems that you should skip 1 byte (you read the stream at the wrong position).

// 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);

Outcome:

 0.20510765305298   
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

For this case I think you have to look at the issue of marshalling .

C# marshalling (C# call C++ DLL)

https://www.codeproject.com/Questions/1201571/Csharp-marshalling-Csharp-call-Cplusplus-DLL

https://mark-borg.github.io/blog/2017/interop/

Community
  • 1
  • 1
Ahmed Msaouri
  • 316
  • 1
  • 10
  • 2
    Please include relevant info in the response in case the links become inaccessible in the future. – orhtej2 Oct 14 '19 at 13:27