现在需要udp 发送一个结构体数据
结构体类型大概如下
struct A
{
int a;
}
struct B
{
int b;
}
struct C
{
A a;
B b;
}
现在要发送 结构体C类型的数据, 请问各位大神,怎样将此类结构体转换为byte数组!
现在需要udp 发送一个结构体数据
结构体类型大概如下
struct A
{
int a;
}
struct B
{
int b;
}
struct C
{
A a;
B b;
}
现在要发送 结构体C类型的数据, 请问各位大神,怎样将此类结构体转换为byte数组!
以下回答参考 皆我百晓生、券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。
在.NET中,你可以使用BitConverter.GetBytes()方法将结构体数据转换为字节数组。以下是一个示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructToByteArrayExample
{
class Program
{
static void Main(string[] args)
{
// 定义一个结构体
struct A
{
public int a;
}
struct B
{
public int b;
}
struct C
{
public A a;
public B b;
}
// 创建一个C类型的对象
C c = new C()
{
a = 1,
b = 2
};
// 将结构体转换为字节数组
byte[] bytes = BitConverter.GetBytes(c);
Console.WriteLine("Byte array: ");
foreach (byte b in bytes)
{
Console.Write(b.ToString("x2") + " ");
}
Console.WriteLine();
}
}
}
在这个例子中,我们首先定义了三个结构体:A、B和C。然后,我们创建了一个C类型的实例,并将其属性的值设置为1和2。最后,我们调用BitConverter.GetBytes()方法将这个C类型的实例转换为一个字节数组,并打印出来。
注意,这个方法会按照字节顺序存储,也就是从最低位开始。所以,如果你的数据是按位序存储的(比如二进制),你需要先进行一些额外的操作来确保它正确地被转换。