1

What is the most efficient way to combine multiple variables of different Types into a single byte-array?

Take the following example data:

short a = 500;
byte b = 10;
byte[] c = new byte[4];

How could I combine these three variables into one byte array without wasting to much time and memory?

Think of it like this (Pseudocode):

var combinedArray = new byte[] { a, b, c };

I thought of different ways, including unsafe code, converting them to byte[] using BitConverter and using Linq's Concat.

I need an array in the end, not just an IEnumerable, because I need to send this data via udp.

Are there any methods I did not think of?

3
  • The BitVector32 .net helper in System.Collections.Specialized can sometimes be useful in these situations. Commented Jun 16, 2018 at 21:19
  • 1
    Use serializers like Json.Net, XmlSerializer, BinaryFormatter etc.... That way you can handle more complex cases you may need in the future.. Commented Jun 16, 2018 at 21:38
  • @Eser Json.Net or XmlSerializer are no options to me, because they generate a lot of bloat and are essentially text, but BinaryFormatter looks promising! Commented Jun 17, 2018 at 8:58

1 Answer 1

4

Use the BinaryWriter combined with a MemoryStream.

var buffer = new MemoryStream();   
var writer = new BinaryWriter(buffer);

writer.Write(a);
writer.Write(b);
writer.Write(c);

writer.Close();    
byte[] bytes = buffer.ToArray();

But do note that there is no padding or alignment. The array c will start at an odd offset.

You will also have to verify the Big Endian / Little Endian contract with your client.

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

6 Comments

If this is sending over udp, i would consider specifying a length of the array at the start and a check sum, however i'm probably being overly pedantic
@TheGeneral - that doesn't depend on the medium, it would entirely depend on the format(s) agreed by sender & receiver. Not specified here. When the array size is fixed and known, you wouldn't add a Length.
Agreed in full, Just putting it out there as although udp is fairly reliable on a local network, there is no guarantee of every packet arriving and ordering. anyway i upvoted
This seems to be a nice solution to me. Will the padding and alignment be an issue, when I am the one sending and recieving the packages? The data sent via udp is in a format that is known to the other side of the connection. If it is an issue, how could I fix it?
When you read with a BinaryReader then there is no issue. But when you control both sides, JSon and XML are alternatives to consider.
|

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.