2

I have a custom protocol to send and receive messages over TCP like the following:

The first 4 bytes is the message type, the following 4 bytes is the length of the message and the rest of the buffer is containing the message itself.

 private byte[] CreateMessage(int mtype,string data)
 {

        byte[] buffer = new byte[4 + 4 + data.Length];

       //write mtype, data.Length, and data to buffer

        return buffer;

 }

I want to write mtype to the first 4 bytes of buffer and then data.Length to next 4 bytes and then the data. I am coming from golang world and we do that like the following:

buf := make([]byte, 4+4+len(data))
binary.LittleEndian.PutUint32(buf[0:], uint32(mtype))
binary.LittleEndian.PutUint32(buf[4:], uint32(len(data)))
3
  • 1
    So basically you're asking how to convert an int to a byte[4] with some certain order to the bytes? Commented Feb 28, 2022 at 19:49
  • 2
    Perhaps just use a BinaryWriter, and write the ints to the network stream; they'll end up as byte sequences on the wire .. Commented Feb 28, 2022 at 19:54
  • @CaiusJard in all seriousness: in something like 18 years specialising in .NET IO code (serializers, network code, etc): I have yet to find a scenario where BinaryWriter is the correct answer to any requirement Commented Feb 28, 2022 at 22:44

1 Answer 1

1
Span<byte> span = buffer;
BinaryPrimitives.WriteUInt32LittleEndian(span, type);
BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(4), (uint)len);
// etc

A span is sort of like an array, and you can create a span from an array..but a span can be sliced internally. Not all APIs work with spans, but those that do ... sweet.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.