Basic Binary Reading

binary-data, binaryfiles, c#

Solution

BinaryReader.ReadInt32 expects the data to be in Little Endian format. Your data you presented is in Big Endian.

Here's a sample program that shows the output of how BinaryWriter writes an Int32 to memory:

namespace Endian {
  using System;
  using System.IO;

  static class Program {
    static void Main() {
      int a = 2051;

      using (MemoryStream stream = new MemoryStream()) {
        using (BinaryWriter writer = new BinaryWriter(stream)) {
          writer.Write(a);
        }

        foreach (byte b in stream.ToArray()) {
          Console.Write("{0:X2} ", b);
        }
      }

      Console.WriteLine();
    }
  }
}

Running this produces the output:

03 08 00 00

To convert between the two, you could read four bytes using `BinaryReader.ReadBytes(4)`, reverse the array, and then use `BitConverter.ToInt32` to convert it to a usable int.

byte[] data = reader.ReadBytes(4);
Array.Reverse(data);
int result = BitConverter.ToInt32(data);

Problem

I am trying to read a file using `BinaryReader`. However, I am having trouble in retrieving the value that is expected. ``` using (BinaryReader b = new BinaryReader(File.Open("file.dat", FileMode.Open))) { int result = b.ReadInt32(); //expected to be 2051 } ``` `"file.dat"` is the following ... ``` 00 00 08 03 00 00 EA 60 ``` The expected result should be `2051`, but it gets something totally irrelevant instead. Note that the result I get everytime is the same. What is the problem?

Original source

Related problems