与下位机通讯时,经常遇到数据转换问题。与下位机通讯时,经常遇到数据转换问题。
参考C语言中(QT语言)
union change
{
float fData;
unsigned int uData;
}r1;
QString strData ="23.9";
r1.d = strData.toFloat();
QString strTransform = QString("%1").arg(r1.m,8,16,QChar('0'));
C#具体上代码实现方式:
//定义4位联合体
[StructLayout(LayoutKind.Explicit, Size = 4)]
public struct UninoCSharp
{
//设置联合体的每一位
[FieldOffset(0)]
public byte b0;
[FieldOffset(1)]
public byte b1;
[FieldOffset(2)]
public byte b2;
[FieldOffset(3)]
public byte b3;
//得到对应的float值
[FieldOffset(0)]
public float fData;
}
初始化:
UninoCSharp uninoCSharp = new UninoCSharp();
初始化数值
float temp = (float)(nudPrice.Value);
uninoCSharp.fData = temp;
定义目标转换数组
private ushort[] registerBuffer;
registerBuffer[0] = (ushort)(uninoCSharp.b1 * 256 + uninoCSharp.b0);
registerBuffer[1] = (ushort)(uninoCSharp.b3 * 256 + uninoCSharp.b2);
应用到通讯中
master.WriteMultipleRegisters(slaveAddress, startAddress, registerBuffer);