参考下面方法
方法1
private int ushortToInt32(ushort[]dat,int start)
{
if( start < 0 || start+1 >= dat.Length)
{
throw new Exception($"ushortToInt32索引超范围{start}");
}
byte[] tmp = new byte[4];
byte[] byteH = BitConverter.GetBytes(dat[start+1]);
byte[] byteL = BitConverter.GetBytes(dat[start+0]);
tmp[0] = byteH[0];
tmp[1] = byteH[1];
tmp[2] = byteL[0];
tmp[3] = byteL[1];
//richTextBox2.Text += $"ushortToInt32 t0={tmp[0]} t1={tmp[1]} t2={tmp[2]} t3={tmp[3]} d0={dat[start + 0]} d1={dat[start + 1]} start = {start} " + "\r\n";
return BitConverter.ToInt32(tmp,0);
}
方法2
private int GetInt32(ushort highOrderValue, ushort lowOrderValue)
{
return BitConverter.ToInt32(BitConverter.GetBytes(lowOrderValue).Concat(BitConverter.GetBytes(highOrderValue)).ToArray(), 0);
}
调用方法
private void button2_Click(object sender, EventArgs e)
{
//ushort[] dat = Bord.ReadHoldingRegisters((ushort)1, (ushort)2);
ushort[] dat = Bord.ReadInputRegisters((ushort)0, (ushort)2*6*3);
//SetMsg(dat);
richTextBox1.Text = "";
//richTextBox2.Text = "";
for (int i = 0; i < dat.Length;i += 2 )
{
richTextBox1.Text += ushortToInt32(dat,i).ToString() + "\r\n";
}
for (int i = 0; i < dat.Length; i += 2)
{
richTextBox1.Text += "GetInt32 " + this.GetInt32(dat[i], dat[i+1]).ToString() + "\r\n";
}
//ModbusUtility.GetUInt32(registers[1], registers[0]);
}
运行结果(与设备通信)
39
17
-5
44
31
8
0
0
0
0
0
0
5
4
4
4
3
3
GetInt32 39
GetInt32 17
GetInt32 -5
GetInt32 44
GetInt32 31
GetInt32 8
GetInt32 0
GetInt32 0
GetInt32 0
GetInt32 0
GetInt32 0
GetInt32 0
GetInt32 5
GetInt32 4
GetInt32 4
GetInt32 4
GetInt32 3
GetInt32 3
注意其中包含 一个负值 -5
其他方法参考 ModbusUtility
//
// 摘要:
// Converts four UInt16 values into a IEEE 64 floating point format.
//
// 参数:
// b3:
// Highest-order ushort value.
//
// b2:
// Second-to-highest-order ushort value.
//
// b1:
// Second-to-lowest-order ushort value.
//
// b0:
// Lowest-order ushort value.
//
// 返回结果:
// IEEE 64 floating point value.
public static double GetDouble(ushort b3, ushort b2, ushort b1, ushort b0)
{
return BitConverter.ToDouble(BitConverter.GetBytes(b0).Concat(BitConverter.GetBytes(b1)).Concat(BitConverter.GetBytes(b2))
.Concat(BitConverter.GetBytes(b3))
.ToArray(), 0);
}
//
// 摘要:
// Converts two UInt16 values into a IEEE 32 floating point format
//
// 参数:
// highOrderValue:
// High order ushort value
//
// lowOrderValue:
// Low order ushort value
//
// 返回结果:
// IEEE 32 floating point value
public static float GetSingle(ushort highOrderValue, ushort lowOrderValue)
{
return BitConverter.ToSingle(BitConverter.GetBytes(lowOrderValue).Concat(BitConverter.GetBytes(highOrderValue)).ToArray(), 0);
}
//
// 摘要:
// Converts two UInt16 values into a UInt32
public static uint GetUInt32(ushort highOrderValue, ushort lowOrderValue)
{
return BitConverter.ToUInt32(BitConverter.GetBytes(lowOrderValue).Concat(BitConverter.GetBytes(highOrderValue)).ToArray(), 0);
}
特此记录
anlog
2022年9月9日