简体   繁体   中英

How to turn a struct into a byte array in c#

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# ?

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 eg Encoding.ASCII if you wish - as long as your C++ consumer can interpret the string on the other end.

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM