Berke Kaan Cetinkaya
Berke Kaan Cetinkaya

Reputation: 828

C# How to write to a byte array starting from index x

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

Upvotes: 2

Views: 385

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062770

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.

Upvotes: 1

Related Questions