2

I need to reproduce in C# a MATLAB code I found, which reads a binary file. The code is:

% Skip header
fread(fid, 1, 'int32=>double', 0, 'b');

% Read one property at the time
i = 0;
while ~feof(fid)
  i = i + 1;

  % Read field name (keyword) and array size
  keyword = deblank(fread(fid, 8, 'uint8=>char')');
  keyword = strrep(keyword, '+', '_');
  num = fread(fid, 1, 'int32=>double', 0, 'b');

  % Read and interpret data type
  dtype = fread(fid, 4, 'uint8=>char')';
End

fclose(fid)

I’ve tried several methods of reading binary files in C#, but I haven’t got the right results. How should I proceed?

this is what i've done, that seems to kind of work so far

        FileStream fs = new FileStream(filename, FileMode.Open);
        BinaryReader binreader = new BinaryReader(fs,Encoding.Default);

        //skip head
        binreader.ReadInt32();
        for (int i = 0; i < 8; i++)
        {
            keyword = keyword + binreader.ReadChar();
        }

        keyword = keyword.TrimEnd();
        keyword = keyword.Replace("+", "_");
        num = binreader.ReadInt32();

        for (int i = 0; i < 4; i++)
        {
            dtype = dtype + binreader.ReadChar();
        }

the problem is that i should obtein: keyword=INTERHEAD, num=411 and dtype=INTE but what Im getting is: keyword=INTERHEAD, num=-1694433280 and dtype=INTE the problem is in getting the num variable right.

I've changed readint32 to readdouble, readUint32 and so on but never got 411.

Any help?

calarez
  • 55
  • 5
  • 1
    This sounds like a very common operation in C#. You should show your attempts in C#, and explain why you think the results are wrong. If possible, please upload/link a small binary file of this type and show what the expected results are. Without doing any of the above, your problem is simply not reproducible and sounds like a code request. – Dev-iL Jul 25 '19 at 07:37
  • Have you tried the documentation? [BinaryReader Class](https://learn.microsoft.com/en-us/dotnet/api/system.io.binaryreader?view=netframework-4.8), and in particular the methods: [ReadChars](https://learn.microsoft.com/en-us/dotnet/api/system.io.binaryreader.readchars?view=netframework-4.8#System_IO_BinaryReader_ReadChars_System_Int32_) and [ReadInt32](https://learn.microsoft.com/en-us/dotnet/api/system.io.binaryreader.readint32?view=netframework-4.8#System_IO_BinaryReader_ReadInt32) – Hoki Jul 25 '19 at 13:13
  • Might it be a problem of reading/receiving wrong `endianness` on the num part? – Paul Efford Dec 27 '21 at 06:07

0 Answers0