2

We are writing a chat application. My friend is doing the server. And for the server to read my message, i have to send the message in bytes with the first 1 byte being the message type and the second 4 bytes being the message length. In Java there is an option to do something like this: ByteArray.allocate(4).putInt(length). Is there anything equivalent to it in c#?

What I have tried:

static byte[] DecimalToByteArray(decimal src)
{
    using (MemoryStream stream = new MemoryStream(4))
    {
        using (BinaryWriter writer = new BinaryWriter(stream))
        {
            writer.Write(src);
            return stream.ToArray();
        }
    }
}
2
  • What does decimal have to do with the question? And why do you need to use decimal? Commented Feb 25, 2017 at 15:03
  • For people who consider this question well-researched - search engine you are using is not up to snuff - bing.com/search?q=c%23+int+to+byte+array Commented Feb 25, 2017 at 15:17

2 Answers 2

1

I would seriously implore you to quit the idea of sending and receiving messages in binary and to use some textual format like xml, json, anything but binary, really.

If you insist on using a binary format, then the BinaryWriter and MemoryStream approach is perfectly fine.

If, for whatever reason, you don't like that, then you can try this:

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the tip. Will try it. The Message is built like this: 1Byte(MessageType) + 4Byte(JSONLength) + JSONMessage. So the Byte is only to check the length of our JSON message
1

There is BitConverter::GetBytes Method (Int32) which converts the integer to an array of 4 bytes.

Unlike Java, you cannot control the endianness of output array. If you need it as little-endian or big-endian, you have to check BitConverter.IsLittleEndian and reverse the array when necessary.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.