繁体   English   中英

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

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

我在c#中有一个带有两个成员的结构:

public int commandID;  
public string MsgData;  

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

在c#中执行此操作的好方法是什么?

以下将返回一个常规字节数组,前四个表示命令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;
}

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

这直接转到字节数组。

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

这将为您提供所需的byte[] 这里需要注意的一件事是我没有使用序列化程序,因为你想要一个非常原始的字符串,并且没有序列化器(我知道)可以将它序列化,就像你想要的OOB一样。 然而,这是一个如此简单的序列化,这更有意义。

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

最后,如果您有更多我不知道的属性,您可以使用反射。

暂无
暂无

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

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