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?
Asked
Active
Viewed 5,903 times
7
-
Uhm, well [Windows only runs on little-endian machines](http://blogs.msdn.com/b/larryosterman/archive/2005/06/07/426334.aspx) and so does Microsoft's .NET framework. Mono might be a different story. – Christian.K Mar 08 '12 at 13:55
-
6@Christian.K: Wrong. The XBox 360 is big endian. – jason Mar 08 '12 at 13:57
-
1@Jason Wow, looks like I was too "focused" (not to say narraw-minded) here. Thanks. – Christian.K Mar 08 '12 at 13:58
-
There's little reason to assume the MSDN article is wrong. It is not. – Hans Passant Mar 08 '12 at 14:05
2 Answers
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