我们正在编写一个聊天应用程序。我 friend 是做服务器的。为了让服务器读取我的消息,我必须以字节为单位发送消息,其中第一个 1 个字节是消息类型,第二个 4 个字节是消息长度。在 Java 中,有一个选项可以执行类似的操作:ByteArray.allocate(4).putInt(length)。 c# 中是否有与它等效的东西?
我尝试过:
static byte[] DecimalToByteArray(decimal src)
{
using (MemoryStream stream = new MemoryStream(4))
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(src);
return stream.ToArray();
}
}
}
最佳答案
我真诚地恳求您放弃以二进制方式发送和接收消息的想法,并使用一些文本格式,例如 xml、json,除了二进制之外的任何格式。
如果您坚持使用二进制格式,那么 BinaryWriter
和 MemoryStream
方法非常合适。
如果出于某种原因您不喜欢这样,那么您可以尝试以下方法:
byte[] bytes = new byte[5];
bytes[0] = messageType;
bytes[1] = (byte)(messageLength & 0xff);
bytes[2] = (byte)((messageLength >> 8) & 0xff);
bytes[3] = (byte)((messageLength >> 16) & 0xff);
bytes[4] = (byte)((messageLength >> 24) & 0xff);
关于c# - 将int写入byte,长度为4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42457532/