Reputation: 2234
I have a structure in c# with two members:
public int commandID;
public string MsgData;
I need to turn both these into a single byte array which then gets sent to a C++ program that will unpack the bytes , it will grab the first `sizeof(int) bytes to get the commandID and then the rest of the MsgData will get used.
What is a good way to do this in c# ?
Upvotes: 4
Views: 1040
Reputation: 5116
This directly goes to a byte array.
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;
}
Upvotes: 1
Reputation: 50114
The following will just return a regular array of bytes, with the first four representing the command ID and the remainder representing the message data, ASCII-encoded and zero-terminated.
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 switch out Encoding.UTF8
for e.g. Encoding.ASCII
if you wish - as long as your C++ consumer can interpret the string on the other end.
Upvotes: 4
Reputation: 67898
This will get you the byte[]
that you want. One thing to note here is I didn't use a serializer because you wanted a very raw string and there are no serializers (that I know of) that can serialize it quite like you want OOB. However, it's such a simple serialization this makes more sense.
var bytes = Encoding.UTF8.GetBytes(string.Format("commandID={0};MsgData={1}", o.commandID, o.MsgData));
Finally, if you had more properties that are unknown to me you could use reflection.
Upvotes: 0