2

I am currently making an application that is required to save an array of float values to a binary file in C# and then open that same binary and retrieve the values in a C program.

I am using a BinaryWriter in C#

binaryWriter.Write(myFloatVar); 

And I am using fread in C

fread(&myfloat, sizeof(float), 1, file);

For the majority it works fine, but when trying to fread a particular value the output comes out strange. The input is 0.6045232 on the C# side as found through debuging, but when it is retrieved on the C program side it appears as 6.961e-041#DEN

I know the DEN means that it is a denormalised number, but I am unsure how this has happened or how to fix it. Any help would be appreciated.

4
  • 3
    Using binary for this is a bad idea, since it assumes that C# and C use the same binary format and same endianness for floating point numbers. There is no guarantee that's the case. In fact, there's no guarantee that a float is even the same size in C# and C. So you should write/read in text format. Commented Feb 6, 2016 at 0:54
  • 2
    It's pretty implausible that your approach "works fine" for most values but fails miserably for one specific one, or even for a small subset. I'm inclined to guess that you noticed the one you asked about because it turned out to be denormalized, but that your C readback of all the numbers is wrong. Commented Feb 6, 2016 at 1:23
  • @John Bollinger It is not implausible. Simply opening one file in binary and the other in text mode is sufficient to first mess up 1 in 64 floats - and then the rest. Commented Feb 6, 2016 at 4:39
  • @user3386109 Writing/reading float as text has its failure modes too. IEEE FP formats are extremely well defined, not so with textual FP ones. Just start looking as C# text of Infinity, de-normal, and insufficient and decimal wobbling precision. Typically the best text is for binary FP to write in a textual binary FP format, like with %a. Assuming C# and C (on the same computer) use the same binary format is not a bad assumption. The exchange file could specify the FP format. Many factors go into the determining what is best. Commented Feb 6, 2016 at 4:50

2 Answers 2

3

A usual case where most FP works fine, especially in the MS world, is one where one of the files is operating in text mode and the other binary.

For the C side, insure the file is open in binary

// FILE *istream = fopen(fileanme, "r");  // r
FILE *istream = fopen(fileanme, "rb");    // rb

Check the C# side too.


Example

int main(void) {
  union {
      float f;
      uint32_t u32;
  } u;
  u.f = 0.60452329;
  printf("0x%08lX %.9e\n", (unsigned long) u.u32, u.f);
  return 0;
}

Output

//      \n  Gets converted to \r\n and messes up the rest of the file
//      vv
0x3F1AC20A 6.045233011e-01
Sign up to request clarification or add additional context in comments.

1 Comment

This was actually the problem in my case, thank you for your help.
1

Agreeing with comment above, this example uses ASCII, not binary, but here is a very simple (with no error checking or handling) example of how to write a float to a file in C#, and read it back using ANSI C:

//C#
string path = @"c:\temp\MyNumber.txt";

if (!File.Exists(path))
{
    // Create a file to write to.
    string number = "4.243523";
    File.WriteAllText(path, number);
}

//ANSI C
char line[80];
char *dummy;
FILE *fp = fopen("c:\\temp\\MyNumber.txt", "r");
if(fp)
{
    if(fgets(line, 80, fp)
    {
        double num = strtod(line, &dummy);  
    }
    ...

2 Comments

1) This does not show "how to write a float to a file in C#" It shows how to write a string in C#. The missing conversion from float to string may appear trivial but is too often done lacking sufficient or excess precision to recover the original float. 2) Converting from a string to double and then to float may incur double rounding. Going directly from a string to float, OP's target type, with strtof() is better than strtod().
While this works, the rational for using binary instead of Unicode or ascii was the the file size would be smaller. The project writes rather large files, so the overhead does slow the program down somewhat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.