简体   繁体   English

如何在c#中将结构转换为字节数组

[英]How to turn a struct into a byte array in c#

I have a structure in c# with two members: 我在c#中有一个带有两个成员的结构:

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. 我需要将这两个转换为单个字节数组,然后将其发送到将解包字节的C ++程序,它将获取第一个`sizeof(int)字节以获取commandID,然后其余的MsgData将被使用。

What is a good way to do this in c# ? 在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. 以下将返回一个常规字节数组,前四个表示命令ID,其余表示消息数据,ASCII编码和零终止。

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. 如果您愿意,可以将Encoding.UTF8切换为例如Encoding.ASCII - 只要您的C ++使用者可以解释另一端的字符串。

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. 这将为您提供所需的byte[] 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. 这里需要注意的一件事是我没有使用序列化程序,因为你想要一个非常原始的字符串,并且没有序列化器(我知道)可以将它序列化,就像你想要的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. 最后,如果您有更多我不知道的属性,您可以使用反射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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