Search code examples
c#c++binaryreader

Error in conversion from binary value to double in c#


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?


Solution

  • 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