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();
        }
    }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
TheWaII
  • 29
  • 7
  • What does `decimal` have to do with the question? And why do you need to use `decimal`? – Mike Nakis Feb 25 '17 at 15:03
  • For people who consider this question well-researched - search engine you are using is not up to snuff - https://www.bing.com/search?q=c%23+int+to+byte+array – Alexei Levenkov Feb 25 '17 at 15:17

2 Answers2

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);
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • 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 – TheWaII Feb 25 '17 at 14:59
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.

cshu
  • 5,654
  • 28
  • 44