目的:
使用C#语言,
如何将一段buffer方便地转换为一个结构体?反过来转换呢?
如何实现一段字节数组与其他类型数组(如short型)的方便转换?
一、 结构体和字节数组互换
参考:
1.1 结构体转换为字节数组
1 | public static byte[] StructToBytes(object structObj) |
1.2 字节数组转换为结构体
1 | public static object BytesToStruct(byte[] bytes, int startIndex, Type strcutType) |
二、相同buffer,不同数据类型
定义一个可按字节数组或short数组存取数据的结构体:1
2
3
4
5
6
7
8[StructLayout(LayoutKind.Explicit, Pack = 2)]//Pack表示最小移动为2字节
public struct AudioDataBuffer
{
[FieldOffset(0)]
public byte[] ByteData;
[FieldOffset(0)]
public short[] ShortData;
}
调用:1
2
3
4
5
6
7
8
9
10
11
12public class Program
{
static void Main(string[] args)
{
AudioDataBuffer Data=new AudioDataBuffer();
Data.ByteData=new byte[1000];
Data.ByteData[0]=1;
Data.ByteData[1]=1;
Console.Write(Data.ShortData[0]);
Console.ReadKey();
}
}
输出结果为:257,即1 0000 0001。