Question

I am puzzled with a particular BinaryReader operation.

When viewing a binary file with a hex editor (UltraEdit), the first four bytes are: 52 62 38 11.

When iterating over the same file with a BinaryReader, if I call ReadInt32() first, I would expect the int value to be 1,382,168,593.

.ReadInt32(): Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes.

Instead, I get 288,907,858.

Clearly I am missing something obvious... can anyone explain what is going on?

Was it helpful?

Solution

BinaryReader reads bytes in little-endian order.

Observe:

csharp> 0x52623811;  // What you expected it to read.
1382168593
csharp> 0x11386252;  // What it actually read.
288907858

If you need to specify the byte ordering of the data you are reading, I would suggest using Mono.DataConvert. I've used it in several projects and it is incredibly useful, as well as MIT-licensed. (It does use unsafe code for performance reasons, so you can't use it in untrusted contexts.)

See the Wikipedia article on endianness for more info on the concept.

See Microsoft's Reference Source for details on the implementation of BinaryReader

OTHER TIPS

Intel architecture is little endian. The last byte in the sequence has the highest value. So 52 62 38 11 is equivalent to 0x11386252.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top