c#如何解决这样的问题?

来源:百度知道 编辑:UC知道 时间:2024/09/20 16:54:03
我现在从串口接收到一组返回值存放在数组中:
Byte[] mbyte = new Byte[23];
serialPort.Read(mbyte, 0, 23);
mbyte中的内容是(16进制表示):
AA F1 89 1 0 0 0 0 0 0 0 0 0 0 0 0 3F 31 EB 85 13 A0 FF

现在定义一个结构:
struct retu
{
public byte a;//数据头1
public byte b;//下位机地址
public byte c;//命令
public byte d;//状态1
public float e;//力4
public float f;//电压
public float g;//电流
public float h;//运动时间
public byte i;//数据长度
public byte Verify;//校验
public byte j;//数据尾
}
就够大小也为23个字节(byte占1字节,float占4字节)。

数组与结构的对应关系是:
public byte a;//数据头1 AA
public byte b;//下位机地址 F1
public byte c;//命令 89
public byte d;//状态 1
public float e;//力 0 0 0 0
public float f;//电压 0 0 0 0
public float g;//电流 0 0 0 0
public float h;//运动时间 3F 31 EB 85
public byte i;//

赋值:
retu.a=mbyte[0];
.......
取值:
string aa=retu.a.ToString();

Byte[] mbyte = new Byte[23];
IntPtr buffer = Marshal.AllocHGlobal(23);
for (int i = 0; i < 23; i++)
{
Marshal.WriteInt32(new IntPtr(buffer.ToInt32() + i), mbyte[i]);
}
Marshal.PtrToStructure(buffer, typeof(retu));