How to turn a structure into an array of bytes in C #

I have a structure in C # with two members:

public int commandID; public string MsgData; 

I need to turn both of these elements into a single byte array, which is then sent to a C ++ program that decompresses the bytes, and will capture the first bytes sizeof (int) to get the commandID, and then the rest of the MsgData will be used.

What is a good way to do this in C #?

+4
source share
3 answers

Next, a regular array of bytes will be returned, with the first four representing the command identifier and the remainder representing the message data encoded in ASCII and ending with zero.

 static byte[] GetCommandBytes(Command c) { var command = BitConverter.GetBytes(c.commandID); var data = Encoding.UTF8.GetBytes(c.MsgData); var both = command.Concat(data).Concat(new byte[1]).ToArray(); return both; } 

You can disable Encoding.UTF8 , for example. Encoding.ASCII , if you want - as long as your C ++ consumer can interpret the line at the other end.

+4
source

This directly relates to an array of bytes.

 public byte[] ToByteArray(int commandID, string MsgData) { byte[] result = new byte[4 + MsgData.Length]; result[0] = (byte)(commandID & 0xFF); result[1] = (byte)(commandID >> 8 & 0xFF); result[2] = (byte)(commandID >> 16 & 0xFF); result[3] = (byte)(commandID >> 24 & 0xFF); Encoding.ASCII.GetBytes(MsgData.ToArray(), 0, MsgData.Length, result, 4); return result; } 
+1
source

This will give you the byte[] you want. It is worth noting here that I did not use a serializer, because you need a very crude string, and there are no serializers (that I know) that can serialize it the same way you want OOB. However, such a simple serialization makes sense.

 var bytes = Encoding.UTF8.GetBytes(string.Format("commandID={0};MsgData={1}", o.commandID, o.MsgData)); 

Finally, if you have more properties unknown to me, you can use reflection.

0
source

Source: https://habr.com/ru/post/1437366/


All Articles