C# BinaryWriter - and endianness
Asked Answered
V

3

15

I am using BinaryWriter in my code, here is my code:

static void Main(string[] args)
{
    FileInfo file = new FileInfo(@"F:\testfile");
    if (file.Exists) file.Delete();
    using (BinaryWriter bw = new BinaryWriter(file.Create()))
    {
        ushort a = 1024;
        ushort b = 2048;
        bw.Write(a);
        bw.Write(b);
        bw.Write(a);
        bw.Write(b);
    }
    Console.ReadLine();
}

But the hex of the output file is :

enter image description here

enter image description here

Isn't that 0x0004 = 4? why?

Vachel answered 10/3, 2016 at 7:11 Comment(0)
M
14

Although 1024 is 0x0400. When it comes to storing this in file or memory, question comes should we use little endian or big endian notation?

In case of BinaryWriter, it is little endian. Which means LSB goes first - then comes the MSB. Hence, it is stored as:

LSB | MSB
00    04

You can read more about endianness.

Metronome answered 10/3, 2016 at 7:14 Comment(2)
I know this is a little late, but as for the BinaryWriter and any other writer class use the constructor that takes a encoding too.. Then use Encoding.BigEndianUnicode to write in big endian instead.Uchish
@Uchish have you tested this? The Encoding.BigEndianUnicode is simply a test encoding for when you call WriteString(). I very seriously doubt that it affects endianness on other methods, especially since MSDN doesn't mention it.Romilly
F
11

As a sidenote, it writes to the file exactly as it is specified in the msdn:

Remarks

BinaryWriter stores this data type in little endian format.

What you asked for is "big endian format". You'll have to reimplement the BinaryWriter to do it.

Note that BinaryWriter has a different behavior from BitConverter. BinaryWriter is "always little endian", while BitConverter.GetBytes(ushort) (that is a totally different function but that has a "common" connection: converting numbers to bytes) is "local-endian" (so it uses the endianness of the computer)

Note

The order of bytes in the array returned by the GetBytes method depends on whether the computer architecture is little-endian or big-endian.

In the end on Intel/AMD PCs this difference is moot: Intel is Little Endian, so are nearly all the cellular phones. The only big exception that I know that supports .NET (in a special version) is the Xbox360.

Fantom answered 10/3, 2016 at 7:40 Comment(0)
M
4

If I'm not mistaken, in the display the endian-ness of the output is reversed with respect to your expectation. Although the hexadecimal representation of 1024 is 0400, it might be stored as 0004, depending on the endian-ness of the encoding or platform.

Midkiff answered 10/3, 2016 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.