Search code examples
c#endiannessbinarywriter

C# BinaryWriter - and endianness


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?


Solution

  • 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.