将int写入长度为4的字节

时间:2017-02-25 14:50:02

标签: c# arrays stream

我们正在撰写聊天应用程序。我的朋友在做服务器。并且为了服务器读取我的消息,我必须以字节为单位发送消息,其中前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();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

BitConverter::GetBytes Method (Int32)可将整数转换为4个字节的数组。

与Java不同,您无法控制输出数组的字节顺序。如果你需要它作为little-endian或big-endian,你必须检查BitConverter.IsLittleEndian并在必要时反转数组。

答案 1 :(得分:0)

我会严肃地恳求你放弃以二进制方式发送和接收消息的想法,并使用一些文本格式,如xml,json,除了二进制之外的任何东西,真的。

如果您坚持使用二进制格式,那么BinaryWriterMemoryStream方法就可以了。

如果出于某种原因,你不喜欢这样,那么你可以试试这个:

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);