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?
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:
Running this produces the output:
To convert between the two, you could read four bytes using
BinaryReader.ReadBytes(4), reverse the array, and then useBitConverter.ToInt32to convert it to a usable int.