For BinaryReader.ReadInt32() and BinaryReader.ReadSingle() the documentation of .Net says:
BinaryReader reads this data type in little-endian format.
So I reason that the BinaryReader will read this data types in little-endian format even if my computer architecture (verified by BitConverter.isLittleEndian) were based on big-endian format.
But for BinaryReader.ReadChars() (returning Char[]) and BinaryReader.PeekChar() (returning Int32) there are no remarks about the byte order.
Now I'm not sure if these methods interpreting bytes depending on the computer architecture or if they are little-endian based, too. Especially I am confused about BinaryReader.PeekChar() that returns the same data type like BinaryReader.ReadInt32(). So it would make sense that this method also reads bytes in little-endian format.
Imagine this situation: My application is running on a big-endian based computer architecture and tries to read a big-endian based binary file. In this case I would have to reverse the byte order for BinaryReader.ReadInt32() and BinaryReader.ReadSingle() (see code below). But do I have to do the same thing for BinaryReader.PeekChar() and BinaryReader.ReadChars()? Unfortunately I don't have a computer / operatingsystem which is based on big-endian. But my application should be compatible to this architecture.
public class ReverseBinaryReader: BinaryReader
{
public ReverseBinaryReader(Stream stream, Encoding encoding) : base(stream, encoding) { }
public override int ReadInt32()
{
var data = base.ReadBytes(4);
Array.Reverse(data);
return BitConverter.ToInt32(data, 0);
}
public override float ReadSingle()
{
var data = base.ReadBytes(4);
Array.Reverse(data);
return BitConverter.ToSingle(data, 0);
}
}
Encodingthat is being used, which is a parameter when constructing the reader. - Marc Gravell♦