Search code examples
c#memorystreambinarywriterbytestream

C# binary writer ushort bytes order


I have a server side app written in D and my client app is written in C#. I use BinaryWriter for communication between them but I have a problem with the byte order.

Actually the order of bytes is not the same, example :

C# Client:

MemoryStream ms = new MemoryStream();
BinaryWriter writer = new BinaryWriter(ms);
writer.Write((ushort)0x01);
writer.Write("test");

Client Output:

[1, 0, 4, 116, 101, 115, 116]

Server output:

[0, 1, 0, 4, 116, 101, 115, 116]

For the client the first 2 bytes have been inverted and the string in my server app is encoded with ushort for length, it is possible to 'modify' the behavior of the BinaryWriter or do I have to create my own implementation?

Edit: Server side the packet serializer: https://github.com/Adwelean/EmperadorServer/blob/master/source/vendor/cerealed/cerealiser.d


Solution

  • According to the MSDN document, BinaryWriter stores UInt16 in little endian format. So it is possible to have a reversed written byte order.

    https://msdn.microsoft.com/en-us/library/8sh9zw1e(v=vs.110).aspx

    I think you can refer to this post for how to use big endian for the writer.

    BinaryWriter Endian issue