简体   繁体   English

C#二进制编写器Ushort字节顺序

[英]C# binary writer ushort bytes order

I have a server side app written in D and my client app is written in C#. 我有一个用D编写的服务器端应用程序,而我的客户端应用程序是用C#编写的。 I use BinaryWriter for communication between them but I have a problem with the byte order. 我使用BinaryWriter在它们之间进行通信,但是字节顺序有问题。

Actually the order of bytes is not the same, example : 实际上字节的顺序是不一样的,例如:

C# Client: C#客户端:

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? 对于客户端,前2个字节已被反转,并且服务器应用程序中的字符串使用ushort进行了长度编码,可以“修改” BinaryWriter的行为,还是必须创建自己的实现?

Edit: Server side the packet serializer: https://github.com/Adwelean/EmperadorServer/blob/master/source/vendor/cerealed/cerealiser.d 编辑:服务器端数据包序列化器: https : //github.com/Adwelean/EmperadorServer/blob/master/source/vendor/cerealed/cerealiser.d

According to the MSDN document, BinaryWriter stores UInt16 in little endian format. 根据MSDN文档,BinaryWriter以小字节序格式存储UInt16。 So it is possible to have a reversed written byte order. 因此,可能会有相反的写入字节顺序。

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

I think you can refer to this post for how to use big endian for the writer. 我想您可以参考这篇文章,了解如何为作者使用big endian。

BinaryWriter Endian issue BinaryWriter Endian问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM