0

Please see this file using Hex Editor:

Hex dump

I am reading the 2 bytes this way:

BinaryReader binaryReader;
int wlen = binaryReader.ReadUInt16();

When I read this 2 bytes my BinaryReader.BaseStream.Position is 14 but wlen = 16384 and this should be 64. What am I doing wrong?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
david hol
  • 1,272
  • 7
  • 22
  • 44

2 Answers2

3

Your data file appears to be produced by some big-endian writer, while BinaryReader reads data assuming the little-endian representation.

If you have control over the format of the file, changing the writer to produce little endian representation would let you avoid making changes to your C# program.

There are several ways to read big-endian data in .NET, too. You could use BitConverter, but reversing the bytes manually is probably the most performant one:

public static short ToInt16Be(byte[] buf, int pos) {
    return (short)(buf[pos]<<8 | buf[pos+1]);
}
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

binaryReader.ReadUInt16() reads using little endian.

See: https://msdn.microsoft.com/en-us/library/system.io.binaryreader.readuint16(v=vs.110).aspx

fjardon
  • 7,921
  • 22
  • 31