Basic binary reads

I am trying to read a file using BinaryReader . However, I am having trouble finding the expected value.

 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 instead, he gets something completely unnecessary. Please note that the result that I get every time is the same.

What is the problem?

+4
source share
4 answers

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

Here is an example program that shows the output of how BinaryWriter writes 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 them between two, you can read four bytes using BinaryReader.ReadBytes(4) , cancel the array , and then use BitConverter.ToInt32 to convert it to a useful int.

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

00 00 08 03 - 2051, but if the bytes are actually in the file in the specified order, they are in the wrong order. The four-byte integer 0x0803 should be stored as 03 08 00 00 - the least significant byte or "low-end".

Offline I suspect you got 50855936 as an answer? This is 00 00 08 03 in importance byte order, "big-endian".

The x86 architecture is little oriented; most other architectures are big-endian. Most likely, your data file was either saved on a large machine or was explicitly saved in big-endian format, since this is the standard byte order for the "Internet".

To convert from big-endian to little-endian, you just need to switch the order of four bytes. The easiest way to do this is the IPAddress.NetworkToHostOrder method (the "network" order is big-endian, the "host" order for x86 is the reverse byte order.)

+5
source

According to MSDN, BinaryReader.ReadInt32 insignificant. Try the following:

 using (BinaryReader b = new BinaryReader(File.Open("file.dat", FileMode.Open))) { int result = IPAddress.NetworkToHostOrder(b.ReadInt32()); //expected to be 2051 } 
+3
source

You can use BitConverter.IsLittleEndian to authenticate the machine your code is running on. If this is not the same endianess as the file you are loading, you will need to cancel the bytes before trying to convert it to int .

+2
source

Source: https://habr.com/ru/post/1446989/


All Articles