7

Microsoft documentation on BinaryReader for ReadUnt32 (for example) states: Reads a 4-byte unsigned integer from the current stream using little-endian encoding. However, is this always correct, even on big-endian systems?

tgiphil
  • 1,242
  • 10
  • 22

2 Answers2

9

The documentation is certainly a hint that implementors on other platforms should use little-endian encoding, and Mono seems to respect this:

public virtual uint ReadUInt32() {
FillBuffer(4);

return((uint) (m_buffer[0] |
           (m_buffer[1] << 8) |
           (m_buffer[2] << 16) |
           (m_buffer[3] << 24)));
}
Joe
  • 122,218
  • 32
  • 205
  • 338
6

Directly from the documentation for BinaryReader.ReadUInt32:

BinaryReader reads this data type in little-endian format.

Note that there is no qualification about the underlying endianness of the machine. It doesn't matter if the underlying system is big endian (say XBox 360), BinaryReader will read in little endian.

In fact, if you tear apart the source you'll see:

public virtual long ReadInt64() {
    this.FillBuffer(4);
    uint num = (uint) (((this.m_buffer[0] |
              (this.m_buffer[1] << 0x08)) |
              (this.m_buffer[2] << 0x10)) |
              (this.m_buffer[3] << 0x18));
    return num;
}

showing very clear it ignores endianness.

Now, what will vary from little endian to big endian machines is BitConverter.ToUInt32. The output will respect the underlying endianness of the machine.

jason
  • 236,483
  • 35
  • 423
  • 525