tgiphil
tgiphil

Reputation: 1252

Is .NET BinaryReader always little-endian, even on big-endian systems?

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?

Upvotes: 7

Views: 6335

Answers (2)

jason
jason

Reputation: 241583

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.

Upvotes: 6

to StackOverflow
to StackOverflow

Reputation: 124686

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)));
}

Upvotes: 9

Related Questions